How to generate multiple function names? [duplicate] - python

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 5 years ago.
I have a number of functions called func_1, func_2, ... I'd like to call each of them in a for loop.
I could do:
for f in [func_1, func_2, func_3]:
print f('foo', 'bar')
but I'd like less typing. Is there any way to generate the names, something like:
for f in ['func_%s' % range(1,5)]:
print f('foo', 'bar')
This fails with 'str' object is not callable, but is there anything like this that works?
EDIT: I'm testing a number of alternative versions of func. They are all supposed to give the same result, but with different implementations. I control the inputs and this is not in production.
However, this is bad and possibly dangerous practice in other contexts. See the comments and answers.

You could look them up in the local scope:
for f in ['func_%s' % range(1,5)]:
print locals()[f]('foo', 'bar')
The locals() function returns a dictionary of names to values in the local scope. If they are global functions, use globals().

You can use eval. However it is very dangerous to use eval. Be careful while playing with it.
for f in ['func_%s' % range(1,5)]:
print eval(f)('foo', 'bar')

Related

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".

exec() and variable scope [duplicate]

This question already has answers here:
How to get local variables updated, when using the `exec` call?
(3 answers)
Closed 3 years ago.
I'm sure this has been asked and answered, but I couldn't find it specifically:
I'm just picking up Python and I'm not understanding a variable scope issue.
I've simplified the problem to the following:
Case 1:
def lev1():
exec("aaa=123")
print("lev1:",aaa)
lev1()
Case 2:
def lev1():
global aaa
exec("aaa=123")
print("lev1:",aaa)
lev1()
Case 3:
def lev1():
exec("global aaa ; aaa=123")
print("lev1:",aaa)
lev1()
Case 1 and Case 2 have aaa undefined in the print statement.
Case 3 works. Where does aaa actually exist in Case 1 and Case 2?
Is there a way to access aaa in Case 1 without a global declaration?
From the docs:
Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.
In other words, if you call exec with one argument, you're not supposed to try to assign any variables, and Python doesn't promise what will happen if you try.
You can have the executed code assign to globals by passing globals() explicitly. (With an explicit globals dict and no explicit locals dict, exec will use the same dict for both globals and locals.)
def lev1():
exec("aaa=123", globals())
print("lev1:", aaa)
lev1()

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.

Python variable scope in if-statements [duplicate]

This question already has answers here:
What's the scope of a variable initialized in an if statement?
(7 answers)
Closed 3 years ago.
In Python, are variable scopes inside if-statements visible outside of the if-statement? (coming from a Java background, so find this a bit odd)
In the following case, name is first defined inside the if-block but the variable is visible outside of the if-block as well. I was expecting an error to occur but 'joe' gets printed.
if 1==1:
name = 'joe'
print(name)
if statements don't define a scope in Python.
Neither do loops, with statements, try / except, etc.
Only modules, functions and classes define scopes.
See Python Scopes and Namespaces in the Python Tutorial.
Yes, in Python, variable scopes inside if-statements are visible outside of the if-statement.
Two related questions gave an interestion discussion:
Short Description of the Scoping Rules?
and
Python variable scope error
All python variables used in a function live in the function level scope. (ignoring global and closure variables)
It is useful in case like this:
if foo.contains('bar'):
value = 2 + foo.count('b')
else:
value = 0
That way I don't have to declare the variable before the if statement.

Why does Python require the "self" parameter? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
python ‘self’ explained
Why do you need explicitly have the “self” argument into a Python method?
Why does Python require the "self" parameter for methods?
For example def method_abc(self, arg1)
And is there ever a date that the need for it will be removed?
Python gives you the option of naming it something other than self, even though the standard is to name it self. Just as it gives you the option of using tabs for indents, even though the standard is to use spaces.
In other words, it's not just "assumed" because...
To give you naming flexibility
To make it clearer that something will be passed self (or not).

Categories

Resources