Create python function with name from array [duplicate] - python

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 3 years ago.
I want to create functions (def $name:) where name comes from array=['str1', 'str2', ...].
I tried the code above and already searched on stackoverflow and google but did not find any solution.
array = ['String1', 'String2', ...]
def array[0]:
code1
def array[1]:
code2
String1()
String2()

You can't define a function using a variable. But it turns out that you can rebind functions variable names.
See this post:
How to use a variable as function name in Python
Example of how to do that:
one = 'one'
two = 'two'
three = 'three'
l = [one, two, three]
def some_stuff():
print("i am sure some stuff")
for item in l:
def _f():
some_stuff()
globals()[item] = _f
del _f
one()
two()
three()

Related

How to use a copy of a variable in a closure [duplicate]

This question already has answers here:
Python Argument Binders
(7 answers)
Closed 2 years ago.
In python I can use the nonlocal keyword to make sure that I use the variable from the outer scope, but how do I copy the variable from the outer scope into the closure?
I have code like this:
my_functions_with_parameters = []
for fun_name in my_function_names:
fun = my_functions[fun_name]
def fun_with_parameters():
return fun(1,2,3)
my_functions_with_parameters.append(fun_with_parameter)
My problem is, that each instance of fun_with_parameters calls the last function, i.e., my_functions[my_function_names[-1]], because the variable fun is a reference.
I tried to use fun = copy.deepcopy(my_functions[fun_name]) but it did not change anything and is probably not the best or fastest way.
Try this instead:
my_functions_with_parameters = []
for fun_name in my_function_names:
fun = my_functions[fun_name]
my_functions_with_parameters.append(fun)
Now you can provide the parameters to each fun in my_functions_with_parameters when you loop through them:
for my_fun in my_functions_with_parameters:
my_fun(1,2,3)
Or you can store the parameters with the function in a tuple:
my_functions_with_parameters = []
for fun_name in my_function_names:
fun = my_functions[fun_name]
my_functions_with_parameters.append((fun, 1, 2, 3))
And call via:
for tup in my_functions_with_parameters:
tup[0](tup[1], tup[2], tup[3])

Using a variable outside of a defined function [duplicate]

This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 6 months ago.
If I had a function that I made:
def a():
n = 2*2
How could I access n out of the function without calling a?
You cannot. You will need to define the variable outside of the function, or call the function and return it.
You need to return it, so do:
def a():
n = 2*2
return n
print(a())
Output:
4
You can also do print, but return is better, check this: What is the formal difference between "print" and "return"?

dynamically create methods in python [duplicate]

This question already has answers here:
Creating functions (or lambdas) in a loop (or comprehension)
(6 answers)
Why to use __setattr__ in python?
(7 answers)
Closed 6 months ago.
given the following snippet:
def fun(ret):
return ret
class A:
def __init__(self):
for string in ['a', 'b']:
setattr(self, string, lambda: fun(string))
>>> a = A()
>>> a.a()
'b'
I want a method a() which returns 'a' and a method b() which returns 'b'. As long as I don't use a lambda expression but setting the attribute to a simple string, the association is correct.
I think my intention is clear? So where am I wrong?
In Python, a function will lookup non-local names in the scope where it was defined or in the global scope if the name still does not exist there. If the value associated to the name changed, so will the returned value. Note that this is not specific to lambda functions.
A way around this is to create a closure by writing a helper function.
def fun(ret):
return ret
class A:
def __init__(self):
def apply_fun(item):
return lambda: fun(item)
for string in ['a', 'b']:
setattr(self, string, apply_fun(string))
print(A().a()) # 'a'
Alternative solution
In that particular case, using __getattr__ might be more suited as it is intended to dynamically return attributes.
def fun(ret):
return ret
class A:
def __getattr__(self, item):
if item in ['a', 'b']:
return lambda: fun(item)
print(A().a()) # 'a'

Same method with two different names? [duplicate]

This question already has answers here:
Can one function have multiple names?
(3 answers)
Closed 5 years ago.
I wold like to use same method but two different names.
For example:
def func(a):
print a
def func2(a):
print a
n= "yes"
func(n)
func2(n)
answer should be:
"yes"
"yes"
Would there be any way I can do:
def fun(a) or func2(a):
print a
or something like this?
Python functions are just objects, you can assign one to another name:
def fun(a):
print a
func2 = fun
Now the names func2 and fun reference the same function object, you can call it through either name.
def func(a):
print("a")
n= "yes"
def fun(a):
func(a)
func(n)

How to get a closure to refer to the value that a variable had at the time of its definition [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Creating lambda inside a loop
In the code below, invoking any member of the returned array of closures
prints the number 4.
def go():
x = []
for i in range(5):
def y(): print i
x.append(y)
return x
I would like each member of the closure to print the number that i was when the closure was defined.
One way around this is to use default arguments:
def y(i=i):
print i
Default arguments are evaluated when the function is created, not called, so this works as you'd expect.
>>> i = 1
>>> def y(i=i): print i
...
>>> i = 2
>>> y()
1
A little extra info just for fun:
If you're curious what the defaults are, you can always inspect that with the .func_defaults attribute (__defaults__ in python3.x):
>>> y.func_defaults
(1,)
This attribute is also writeable, so you can in fact change the defaults after the function is created by putting a new tuple in there.

Categories

Resources