Running a Function via concatenation PYTHON [duplicate] - python

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 8 years ago.
So what I'm trying to do is run a function using concatenation like this:
location = 1
"critter_" + location + "()"
and I was hoping that would run the function 'critter_1()' but apparently it doesn't work like that so I tried a couple of stuff since it gave me an error about str to int concatenation error. So what I tried was:
location = 1
"critter_" + int(location) + "()"
And it still didn't work so I came here to ask you guys if there is any way to actually do this.
Any ideas? Thanks!

You can use globals()[function_name] to get function object. Once you get the function object, call it like ordinary name.
func = globals()['critter_{}'.format(location)]
# OR func = globals()['critter_' + str(location)]
func()

You have two separate problems:
You need to get the correct name for the function, so you need to convert your integer 1 to the string '1'. The easiest way is to just use funcname = "critter_"+str(location), although you have more control over the way the conversion is done if you use the format method of the strings. (You've got the meaning of int almost exactly backwards -- it converts to an integer; str converts to a string!)
You need to call the function given by the string. For this, you can use a number of different methods. Simplest is probably just to call eval(funcname+"()"), although this isn't always safe. You can also use funcname to find the function in the dictionary which stores all globally defined function, globals()[funcname].
Alternately, you could make your own list or dictionary of critter_n functions, and select from that:
critter_functions = {1: critter_1, 2: critter_2} #etc...
# ...
location = 1
critter_functions[location]()

Related

Is it possible python strings are not as inmutable as I had thought? [duplicate]

This question already has answers here:
How unique is Python's id()?
(3 answers)
Closed 1 year ago.
I was trying some recursive code in which I create a string outside the first call of my recursive function, and send that string as an argument to said first call. This string gets passed around a ton of times inside a recursive algorithm.
Inside this function, the string is mutated using +=. This function obviously gets called a lot as its recursive. I assumed each modification to the string wouldn't inadvertently affect the other function as += should create a new instance of the string, but it seems that sometimes it does mutate it and affects other calls of my function.
I did some digging around (picture above) and found that when doing += to a function sometimes it keeps its id, though I don't know if this confirms my suspicion.
Anyone have any idea of what could be happening?
This is likely a memory management optimization that keeps the same ID when you are extending the only reference to a string where available memory exists at the end of the string. At some point the preallocated memory block get filled and a new ID needs to be assigned.
To confirm this, if you store a copy of a in a list, you'll see the id change at every iteration (because there is now more than one reference to the string):
a = ""
b = []
for i in range(30):
a += "A"
b.append(a)
print(id(a))

what the difference for function and Procedure in algorithm? [duplicate]

This question already has answers here:
What is the difference between a "function" and a "procedure"?
(18 answers)
Closed 1 year ago.
What the difference for function and Procedure in algorithm ??and how is it defined in python?
please,help me, I am a beginner in programming
In some languages, there is an explicit difference between the two. And the difference is not necessarily the same in all languages where such a difference exists.
In general, when such a distinction exists, it is implied that the function is 'pure', i.e. it always responds with the same output for the same input, and does not alter the state of the surrounding program. Whereas, a procedure, is more to be thought of as a list of commands, which may or may not take parameters, and operates on the existing space, possibly modifying it as a result.
In python there is no such distinction between 'function' and 'procedure', therefore the two can probably be used interchangeably, although presumably the term 'function' would be preferred.
Basically a function is something that calculates or executes a certain task (add a to b), while a procedure is a set of operations you perform in a certain order or depend on each other.
A function takes arguments and returns a value while a procedure does not return values it just performs a set of instructions.
In python they are both declared the same way using the def keyword and you either end it with a return statement if it's a function or not if it's a procedure
Here is an example of both :
function :
def add(a,b):
return a + b
procedure :
def printFullname(firstname,lastname):
print(firstname + ' ' + lastname)

I am new to python, and realized that i can assign print i.e. an inbuilt function as a variable [duplicate]

This question already has answers here:
How to restore a builtin that I overwrote by accident?
(3 answers)
Closed 2 years ago.
I am new to python, and realized that i can assign print i.e. an inbuilt function as a variable, then when i use print('hello world')this shows the exact error that i faced
I am familiar to c++ and even in that we were never allowed to use an inbuilt function as a variable name.
those were the fundamental rules for naming a variable
If python.org has issued the new version I'm sure they would have done it for a reason, bbut i want to know how do i access my print statement after assigning a value to it?
you won't be able to access your print function unless you do hacky things, which I recommend not to do them in the middle of your code.
Also it is good to know that python (as c++) has scopes for variables, and variables "die" and they are no longer accessible when scope ends. For instance:
def change_print_value():
print = 3
change_print_value()
print('Print works as expected')
It is a good practice to avoid using reserved keywords as variable names. Any IDE has the keywords highlighted, so you can easily realize when you are using a keyword where you shouldn't.
print is not part of the reserved keywords list in python. Here's a comprehensive list of reserved words.
Functions are first class objects in python, so that means they can be treated and manipulated as objects. Since print is a function (and an object), when you call print = 1, you reassign the variable print to have a value of 1, so the functionality "disappears".

Do Python functions know how many outputs are requested? [duplicate]

This question already has answers here:
nargout in Python
(6 answers)
Closed 7 years ago.
In Python, do functions know how many outputs are requested? For instance, could I have a function that normally returns one output, but if two outputs are requested, it does an additional calculation and returns that too?
Or is this not the standard way to do it? In this case, it would be nice to avoid an extra function argument that says to provide a second input. But I'm interested in learning the standard way to do this.
The real and easy answer is: No.
Python functions/methods does not know about how many outputs are requested, as unpacking of a returned tuple happens after the function call.
What's quite a best practice to do though is to use underscore (_) as a placeholder for unused args that are returned from functions when they're not needed, example:
def f():
return 1, 2, 3
a, b, c = f() # if you want to use all
a, _, _ = f() # use only first element in the returned tuple, 'a'
_, b, _ = f() # use only 'b'
For example, when using underscore (_) pylint will suppress any unused argument warnings.
Python functions always return exactly 1 value.
In this case:
def myfunc():
return
that value is None. In this case:
def myfunc():
return 1, 2, 3
that value is the tuple (1, 2, 3).
So there is nothing for the function to know, really.
As for returning different outputs controlled by parameters, I'm always on the fence about that. It would depend on the actual use case. For a public API that is used by others, it is probably best to provide two separate functions with different return types, that call private code that does take the parameter.

python introspection - get name of variable passed to function [duplicate]

This question already has answers here:
How to get the original variable name of variable passed to a function [duplicate]
(13 answers)
Closed 7 years ago.
I'd like to be able to access the name of a variable that is passed to a function as e.g.
def f(x):
'''Returns name of list/dict variable passed to f'''
return magic(x)
>>a = [1,2,3]
>>print( f(a) )
'a'
>>print( f(2) )
None
I suspect this is possible using Python introspection but I don't know enough to understand the inspect module. (NB I know that the need for a function like magic() is questionable, but it is what I want.)
Actually, this is not possible. In Python names and values are quite separate. Inside f, you have access to the value of x, but it is not possible to find out what other names other functions might have given to that value.
Think of names as being somewhat like pointers in C. If you have a pointer, you can find out what object it points to. But if you have the object, you cannot find out what pointers are pointing to it.

Categories

Resources