Dynamic attribute lookup may be done by using getattr
function.
def npMethodChooser(n, m, method):
return getattr(np.random.rand(n, m), method)(axis = 1)
Absolutely.
def run_my_function(func, * args, ** kwargs):
return func( * args, ** kwargs)
This function accepts a function func
, any number of inputs which it stores in a list args
and any number of keyword arguments, which it store in a dictionary kwargs
. It then passes those inputs to the function func
and returns that functions return value.
run_my_function(mean, axis = 1)
Just accept the method as a parameter
def npMethodChooser(n, m, method):
result = method(...)
...
In this specific case, the caller function does not yet have a reference to the final method to be called - it knows the method name -
In this case you can pass the desired method name as a string, and retrio eve it from your object using getattr
before calling it:
def npMethodChooser(n, m, method):
obj = np.random.rand(n, m)
result = getattr(obj, method)(axis = 1)
return result
Functions can also be called using keyword arguments of the form kwarg=value. For instance, the following function:,Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:,It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined.,Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored:
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42 >>>
if x < 0:
...x = 0
...print('Negative changed to zero')
...elif x == 0:
...print('Zero')
...elif x == 1:
...print('Single')
...
else:
...print('More')
...
More
>>> # Measure some strings:
...words = ['cat', 'window', 'defenestrate'] >>>
for w in words:
...print(w, len(w))
...
cat 3
window 6
defenestrate 12
# Create a sample collection users = { 'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active' } # Strategy: Iterate over a copy for user, status in users.copy().items(): if status == 'inactive': del users[user] # Strategy: Create a new collection active_users = {} for user, status in users.items(): if status == 'active': active_users[user] = status
>>>
for i in range(5):
...print(i)
...
0
1
2
3
4
>>> list(range(5, 10))[5, 6, 7, 8, 9]
>>>
list(range(0, 10, 3))[0, 3, 6, 9]
>>>
list(range(-10, -100, -30))[-10, -40, -70]
>>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>>
for i in range(len(a)):
...print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
Last Updated : 16 Aug, 2022
Output:
Jan mar
The exec() function can take any source code as a string and run it within your script. It’s the perfect way to dynamically create a function in Python!,First, define the factory function that dynamically creates a local function f only visible within the scope of the current function execution. The function f can do all the custom things you want it to do.,Here’s how you can use the exec() function to define 10 functions programmatically and run them afterwards:,As you can see you can “hard-code” any behavior into the inner function based on the factory arguments to customize how functions are dynamically created.
For example, you may want to define ten functions f_0
, f_1
, …, f_9 programmatically that do something such as printing its function identifier. You could do the following:
def f_0(): print(0)
def f_1(): print(1)
def f_2(): print(2)
def f_3(): print(3)
def f_4(): print(4)
def f_5(): print(5)
def f_6(): print(6)
def f_7(): print(7)
def f_8(): print(8)
def f_9(): print(9)
f_0()
f_1()
f_2()
f_3()
f_4()
f_5()
f_6()
f_7()
f_8()
f_9()
The desired output would be:
0 1 2 3 4 5 6 7 8 9
Here’s how you can use the exec()
function to define 10 functions programmatically and run them afterwards:
# Define functions f_0 to f_9
for i in range(10):
exec(f "def f_{i}(): print({i})")
# Run functions f_0 to f_9
for i in range(10):
exec(f "f_{i}()")
You can use the dir()
function to check out whether the functions are really defined in the namespace:
>>> dir()['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'f_0', 'f_1', 'f_2', 'f_3', 'f_4', 'f_5', 'f_6', 'f_7', 'f_8', 'f_9', 'i']
A more elegant way to solve our problem would be to create a function factory—a function that creates other functions programmatically and returns them as function objects. You can then use the callable objects to run the dynamically-created functions.
# Define factory
def factory(argument):
def f():
print(argument)
return f
# Define functions
functions = []
for i in range(10):
functions.append(factory(i))
# Run functions
for f in functions:
f()