how to print the default value if argument is None in python - python

[sample.py]
def f(name='Hello Guest'):
print(name)
def A(name=None):
f(name)
A()
Expected Output: 'Hello Guest'
Current Output: None
I'm expecting the answers by without using much more codes like 'name = name if name is not None else some_default_value'
Thanks in advance!

Does this work for you?
def f(name):
print(name or 'Hello Guest')
def A(name=None):
f(name)
A()
Out: "Hello Guest"
A("Hello World")
Out: "Hello World"
If the name variable is being used multiple times in the function, you could just reassign it in the beginning of the function. name = name or "Hello Guest"

The best way to do this will be to use a shared default:
DEFAULT_NAME = "Hello Guest"
def f(name=DEFAULT_NAME):
print(name)
def A(name=DEFAULT_NAME):
f(name)

Using inspect.signature to store default is one way to go:
def f(name='Hello Guest'):
print(name or inspect.signature(f).parameters['name'].default)
def A(name=None):
f(name)
A()
# Hello Guest
With some loss of generality, but simpler (shorter and no other lib):
def f(name='Hello Guest'):
print(name or f.__default__[0])
def A(name=None):
f(name)
A()
# Hello Guest

I have been in a similar situation where I can't change the signature or the body of a function I call internally but I want to use the defaults or pass arguments only when they exists(which can get tricky if you plan to pop those keys manually)
This was the cleanest and the most reusable solution I could write.
Simplest solution:
def f(name='Hello Guest'):
print(name)
def A(**kwargs):
# If kwargs has any keys which are None in value, will be removed.
# Keys which don't exists in kwargs won't propagate, hence using default value.
f(**{k:v for k, v in kwargs.items() if v})
A()
# This returns "Hello Guest"
A(**{"name": None})
# This returns "Hello Guest"
A(**{"name": "Someone!"})
# This returns "Someone!"
Inspect solution:
Inspect is a great module if you plan to do something complex with function signature, parameters, etc.
from inspect import signature
# This function is untouched
def f(name='Hello Guest'):
print(name)
# changed the signature so that params can propagate further
def A(**kwargs):
t = signature(f, follow_wrapped=True)
# If kwargs has any key which is None in value,
# it will be replaced with default values for the function.
# Keys which don't exists in kwargs won't propagate.
f(**{k: (v or t.parameters[k].default) for k, v in kwargs.items()})
A()
# This returns "Hello Guest"
A(**{"name": None})
# This returns "Hello Guest"
A(**{"name": "Someone!"})
# This returns "Someone!"

Or
def f(name):
print(name)
def A(name = 'Hello Guest'):
f(name)
A()

Related

Passing functions and image paths into another function in Python [duplicate]

Is it possible to pass a method as a parameter to a method?
self.method2(self.method1)
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun.call()
return result
Yes it is, just use the name of the method, as you have written. Methods and functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.
Since you asked about methods, I'm using methods in the following examples, but note that everything below applies identically to functions (except without the self parameter).
To call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name:
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun()
return result
obj.method2(obj.method1)
Note: I believe a __call__() method does exist, i.e. you could technically do methodToRun.__call__(), but you probably should never do so explicitly. __call__() is meant to be implemented, not to be invoked from your own code.
If you wanted method1 to be called with arguments, then things get a little bit more complicated. method2 has to be written with a bit of information about how to pass arguments to method1, and it needs to get values for those arguments from somewhere. For instance, if method1 is supposed to take one argument:
def method1(self, spam):
return 'hello ' + str(spam)
then you could write method2 to call it with one argument that gets passed in:
def method2(self, methodToRun, spam_value):
return methodToRun(spam_value)
or with an argument that it computes itself:
def method2(self, methodToRun):
spam_value = compute_some_value()
return methodToRun(spam_value)
You can expand this to other combinations of values passed in and values computed, like
def method1(self, spam, ham):
return 'hello ' + str(spam) + ' and ' + str(ham)
def method2(self, methodToRun, ham_value):
spam_value = compute_some_value()
return methodToRun(spam_value, ham_value)
or even with keyword arguments
def method2(self, methodToRun, ham_value):
spam_value = compute_some_value()
return methodToRun(spam_value, ham=ham_value)
If you don't know, when writing method2, what arguments methodToRun is going to take, you can also use argument unpacking to call it in a generic way:
def method1(self, spam, ham):
return 'hello ' + str(spam) + ' and ' + str(ham)
def method2(self, methodToRun, positional_arguments, keyword_arguments):
return methodToRun(*positional_arguments, **keyword_arguments)
obj.method2(obj.method1, ['spam'], {'ham': 'ham'})
In this case positional_arguments needs to be a list or tuple or similar, and keyword_arguments is a dict or similar. In method2 you can modify positional_arguments and keyword_arguments (e.g. to add or remove certain arguments or change the values) before you call method1.
Yes it is possible. Just call it:
class Foo(object):
def method1(self):
pass
def method2(self, method):
return method()
foo = Foo()
foo.method2(foo.method1)
Here is your example re-written to show a stand-alone working example:
class Test:
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun()
return result
def method3(self):
return self.method2(self.method1)
test = Test()
print test.method3()
Use a lambda function.
So if you have no arguments, things become pretty trivial:
def method1():
return 'hello world'
def method2(methodToRun):
result = methodToRun()
return result
method2(method1)
But say you have one (or more) arguments in method1:
def method1(param):
return 'hello ' + str(param)
def method2(methodToRun):
result = methodToRun()
return result
Then you can simply invoke method2 as method2(lambda: method1('world')).
method2(lambda: method1('world'))
>>> hello world
method2(lambda: method1('reader'))
>>> hello reader
I find this much cleaner than the other answers mentioned here.
If you want to pass a method of a class as an argument but don't yet have the object on which you are going to call it, you can simply pass the object once you have it as the first argument (i.e. the "self" argument).
class FooBar:
def __init__(self, prefix):
self.prefix = prefix
def foo(self, name):
print "%s %s" % (self.prefix, name)
def bar(some_method):
foobar = FooBar("Hello")
some_method(foobar, "World")
bar(FooBar.foo)
This will print "Hello World"
Yes; functions (and methods) are first class objects in Python. The following works:
def foo(f):
print "Running parameter f()."
f()
def bar():
print "In bar()."
foo(bar)
Outputs:
Running parameter f().
In bar().
These sorts of questions are trivial to answer using the Python interpreter or, for more features, the IPython shell.
Methods are objects like any other. So you can pass them around, store them in lists and dicts, do whatever you like with them. The special thing about them is they are callable objects so you can invoke __call__ on them. __call__ gets called automatically when you invoke the method with or without arguments so you just need to write methodToRun().
Not exactly what you want, but a related useful tool is getattr(), to use method's name as a parameter.
class MyClass:
def __init__(self):
pass
def MyMethod(self):
print("Method ran")
# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now
# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()
Example: a simple function call wrapper:
def measure_cpu_time(f, *args):
t_start = time.process_time()
ret = f(*args)
t_end = time.process_time()
return t_end - t_start, ret

Functions in dictionaries in python

I can store functions in dictionaries by saying
MyDict = {}
def func():
print("Hello, world!")
MyDict["func"] = func
I was wondering if there was a cleaner/neater way to write this - something along the lines of
MyDict = {}
def MyDict["func"]():
print("Hello, world!")
However this code throws a syntax error
You can (ab)use a decorator.
MyDict = {}
def store(d, name):
def _(f):
d[name] = f
return f
return _
#store(MyDict, "func")
def func():
print("Hello, world!")
#store(MyDict, "foo")
def some_other_func():
print("Goodbye")
You can simplify this if you just want to use the defined name as the key and hard-code the dictionary to update:
def store(f):
MyDict[f.__name__] = f
return f
#store
def func():
print("Hello, world!")
For your example you can do this:
d = {}
d['func'] = lambda: print('Hello, world!')
d['func']()
>>> 'Hello, world!'
If you want to use a class:
class MyClass:
def func(self):
print('Hello, world!')
c = MyClass()
c.func()
>>> 'Hello, world!'
This is wrong:
def MyDict["func"]():
print("Hello, world!")
because after def you need to use some word that contains only allowed characters. That's why you got Syntax error.
What you can use is:
1) Lambda functions (as suggested by #bphi)
MyDict = {}
MyDict['func'] = lambda: print("123")
MyDict['func']()
2) Python class to dynamically create methods (inside the class) which are stored in MyDict, using setattr built-in function:
def func1():
print(1)
def func2():
print(2)
MyDict = {}
MyDict['func1'] = func1
MyDict['func2'] = func2
class MyClass3:
def __init__(self):
for name, obj in MyDict.items():
setattr(self, name, obj)
obj = MyClass3()
obj.func1()
obj.func2()
or via lambda:
MyDict = {}
MyDict['func1'] = lambda : print(1)
MyDict['func2'] = lambda : print(2)
class MyClass3:
def __init__(self):
for name, obj in MyDict.items():
setattr(self, name, obj)
obj = MyClass3()
obj.func1()
obj.func2()
or
class MyClass3:
MyDict = {}
MyDict['func1'] = lambda: print(1)
MyDict['func2'] = lambda: print(2)
def __init__(self):
for name, obj in self.MyDict.items():
setattr(self, name, obj)
obj = MyClass3()
obj.func1()
obj.func2()
If you can express all your functions as one-liners, use lambdas as suggested in #bphi's answer.
If you don't want to be rescricted by using the lambda calculus, another way is to use a class and its static methods. Static methods are methods of a class, not an instance of a class, so they don't have access to the inner state of an object and can be called on the class, not an instance.
However, by reading through this answer you might see why this is not a very elegant (or recommended) approach, even though the result is exactly what you asked for.
class MyClass:
#staticmethod # this decorator is optional here, but suggested for code clarity
def func():
print("Hello, world!")
def func2():
print("Hey there, I am another function.")
MyClass.func()
>>> 'Hello, world!'
MyClass.func()
>>> 'Hey there, I am another function.'
If you want to use the syntax of dictionaries as proposed in your question, you can use __dict__ on the class:
MyDict = dict(MyClass.__dict__)
MyDict["func"]()
>>> 'Hello, world!'
MyDict["func2"]()
>>> 'Hey there, I am another function.'
And you can also add other functions to that dictionary:
MyDict["func3"] = lambda: print("Hi, I am yet another function.")
def func4:
print("And I am the last function for today.")
MyDict["func4"] = func4
MyDict["func"]()
>>> 'Hi, I am yet another function.'
MyDict["func2"]()
>>> 'And I am the last function for today.'
But as this dictionary is just a representation of the class MyClass, it also contains some items related to that class, like __weakref__. But you can extract your own functions:
MyCleanDict = {}
for key, value in MyDict:
if not key.startswith("_"):
MyCleanDict[key] = value
The result is exactly what you asked for, but I doubt the complexity of the approach is worth the result. I recommend a) using lambda-functions, b) staying at your first approach (define the functions first and then put them in a dict) or c) rethink your actual problem as you may find another solution besides storing functions in a dictionary.

Object - orientation

class Mammal(object):
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
def say(self):
print("What does the " + self.name + " says")
The above is my code
when I tried print(Mammal("Fox").say()) I get What does the Fox says which is correct but I am getting another additional None . What is the problem ?
That is because the method say returns None, it simply prints something
None is what is returned by a method in python if it does not have a return statement described
>>> print (Mammal("Fox").say())
None
>>> def a():
... return True
>>> def b():
... pass
>>> print(a())
True
>>> print(b())
None
However, if you want to be more pythonic, you should make your say method return the string rather than say it as follows:
def say(self):
return "What does the " + self.name + " says"
That way you only get the string when you call the method and don't actually print anything:
>>> print(Mammal("Fox").say())
What does the Fox says
However, if you want to stick with printing from the method, you can do it as follows:
Mammal("Fox").say()
or:
fox = Mammal('Fox')
fox.say()
The method say() returns None. It also prints a string itself.
Try:
Mammal("Fox").say()
Another thing to try is extract the string to a method:
def what_should_i_say(self):
return "What does the " + self.name + " says"
def say(self):
print self.what_should_i_say()
and then
print Mammal("Fox").what_should_i_say()
Mammal("Giraffe").say()
Mammal("Fox").say()
is all you need.
Mammal("Fox").say() returns None so you are effectively typing:
print(None)
It just so happens it print the saying to calculate that .say() returns None.
You have added an extra print. Mammal("Fox").say() should work.

How do I pass a method as a parameter in Python

Is it possible to pass a method as a parameter to a method?
self.method2(self.method1)
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun.call()
return result
Yes it is, just use the name of the method, as you have written. Methods and functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.
Since you asked about methods, I'm using methods in the following examples, but note that everything below applies identically to functions (except without the self parameter).
To call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name:
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun()
return result
obj.method2(obj.method1)
Note: I believe a __call__() method does exist, i.e. you could technically do methodToRun.__call__(), but you probably should never do so explicitly. __call__() is meant to be implemented, not to be invoked from your own code.
If you wanted method1 to be called with arguments, then things get a little bit more complicated. method2 has to be written with a bit of information about how to pass arguments to method1, and it needs to get values for those arguments from somewhere. For instance, if method1 is supposed to take one argument:
def method1(self, spam):
return 'hello ' + str(spam)
then you could write method2 to call it with one argument that gets passed in:
def method2(self, methodToRun, spam_value):
return methodToRun(spam_value)
or with an argument that it computes itself:
def method2(self, methodToRun):
spam_value = compute_some_value()
return methodToRun(spam_value)
You can expand this to other combinations of values passed in and values computed, like
def method1(self, spam, ham):
return 'hello ' + str(spam) + ' and ' + str(ham)
def method2(self, methodToRun, ham_value):
spam_value = compute_some_value()
return methodToRun(spam_value, ham_value)
or even with keyword arguments
def method2(self, methodToRun, ham_value):
spam_value = compute_some_value()
return methodToRun(spam_value, ham=ham_value)
If you don't know, when writing method2, what arguments methodToRun is going to take, you can also use argument unpacking to call it in a generic way:
def method1(self, spam, ham):
return 'hello ' + str(spam) + ' and ' + str(ham)
def method2(self, methodToRun, positional_arguments, keyword_arguments):
return methodToRun(*positional_arguments, **keyword_arguments)
obj.method2(obj.method1, ['spam'], {'ham': 'ham'})
In this case positional_arguments needs to be a list or tuple or similar, and keyword_arguments is a dict or similar. In method2 you can modify positional_arguments and keyword_arguments (e.g. to add or remove certain arguments or change the values) before you call method1.
Yes it is possible. Just call it:
class Foo(object):
def method1(self):
pass
def method2(self, method):
return method()
foo = Foo()
foo.method2(foo.method1)
Here is your example re-written to show a stand-alone working example:
class Test:
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun()
return result
def method3(self):
return self.method2(self.method1)
test = Test()
print test.method3()
Use a lambda function.
So if you have no arguments, things become pretty trivial:
def method1():
return 'hello world'
def method2(methodToRun):
result = methodToRun()
return result
method2(method1)
But say you have one (or more) arguments in method1:
def method1(param):
return 'hello ' + str(param)
def method2(methodToRun):
result = methodToRun()
return result
Then you can simply invoke method2 as method2(lambda: method1('world')).
method2(lambda: method1('world'))
>>> hello world
method2(lambda: method1('reader'))
>>> hello reader
I find this much cleaner than the other answers mentioned here.
If you want to pass a method of a class as an argument but don't yet have the object on which you are going to call it, you can simply pass the object once you have it as the first argument (i.e. the "self" argument).
class FooBar:
def __init__(self, prefix):
self.prefix = prefix
def foo(self, name):
print "%s %s" % (self.prefix, name)
def bar(some_method):
foobar = FooBar("Hello")
some_method(foobar, "World")
bar(FooBar.foo)
This will print "Hello World"
Yes; functions (and methods) are first class objects in Python. The following works:
def foo(f):
print "Running parameter f()."
f()
def bar():
print "In bar()."
foo(bar)
Outputs:
Running parameter f().
In bar().
These sorts of questions are trivial to answer using the Python interpreter or, for more features, the IPython shell.
Methods are objects like any other. So you can pass them around, store them in lists and dicts, do whatever you like with them. The special thing about them is they are callable objects so you can invoke __call__ on them. __call__ gets called automatically when you invoke the method with or without arguments so you just need to write methodToRun().
Not exactly what you want, but a related useful tool is getattr(), to use method's name as a parameter.
class MyClass:
def __init__(self):
pass
def MyMethod(self):
print("Method ran")
# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now
# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()
Example: a simple function call wrapper:
def measure_cpu_time(f, *args):
t_start = time.process_time()
ret = f(*args)
t_end = time.process_time()
return t_end - t_start, ret

Calling a function of a module by using its name (a string)

How do I call a function, using a string with the function's name? For example:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
Given a module foo with method bar:
import foo
bar = getattr(foo, 'bar')
result = bar()
getattr can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.
Using locals(), which returns a dictionary with the current local symbol table:
locals()["myfunction"]()
Using globals(), which returns a dictionary with the global symbol table:
globals()["myfunction"]()
Based on Patrick's solution, to get the module dynamically as well, import it using:
module = __import__('foo')
func = getattr(module, 'bar')
func()
Just a simple contribution. If the class that we need to instance is in the same file, we can use something like this:
# Get class from globals and create an instance
m = globals()['our_class']()
# Get the function (from the instance) that we need to call
func = getattr(m, 'function_name')
# Call it
func()
For example:
class A:
def __init__(self):
pass
def sampleFunc(self, arg):
print('you called sampleFunc({})'.format(arg))
m = globals()['A']()
func = getattr(m, 'sampleFunc')
func('sample arg')
# Sample, all on one line
getattr(globals()['A'](), 'sampleFunc')('sample arg')
And, if not a class:
def sampleFunc(arg):
print('you called sampleFunc({})'.format(arg))
globals()['sampleFunc']('sample arg')
Given a string, with a complete python path to a function, this is how I went about getting the result of said function:
import importlib
function_string = 'mypackage.mymodule.myfunc'
mod_name, func_name = function_string.rsplit('.',1)
mod = importlib.import_module(mod_name)
func = getattr(mod, func_name)
result = func()
The best answer according to the Python programming FAQ would be:
functions = {'myfoo': foo.bar}
mystring = 'myfoo'
if mystring in functions:
functions[mystring]()
The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct
The answer (I hope) no one ever wanted
Eval like behavior
getattr(locals().get("foo") or globals().get("foo"), "bar")()
Why not add auto-importing
getattr(
locals().get("foo") or
globals().get("foo") or
__import__("foo"),
"bar")()
In case we have extra dictionaries we want to check
getattr(next((x for x in (f("foo") for f in
[locals().get, globals().get,
self.__dict__.get, __import__])
if x)),
"bar")()
We need to go deeper
getattr(next((x for x in (f("foo") for f in
([locals().get, globals().get, self.__dict__.get] +
[d.get for d in (list(dd.values()) for dd in
[locals(),globals(),self.__dict__]
if isinstance(dd,dict))
if isinstance(d,dict)] +
[__import__]))
if x)),
"bar")()
For what it's worth, if you needed to pass the function (or class) name and app name as a string, then you could do this:
myFnName = "MyFn"
myAppName = "MyApp"
app = sys.modules[myAppName]
fn = getattr(app,myFnName)
Try this. While this still uses eval, it only uses it to summon the function from the current context. Then, you have the real function to use as you wish.
The main benefit for me from this is that you will get any eval-related errors at the point of summoning the function. Then you will get only the function-related errors when you call.
def say_hello(name):
print 'Hello {}!'.format(name)
# get the function by name
method_name = 'say_hello'
method = eval(method_name)
# call it like a regular function later
args = ['friend']
kwargs = {}
method(*args, **kwargs)
As this question How to dynamically call methods within a class using method-name assignment to a variable [duplicate] marked as a duplicate as this one, I am posting a related answer here:
The scenario is, a method in a class want to call another method on the same class dynamically, I have added some details to original example which offers some wider scenario and clarity:
class MyClass:
def __init__(self, i):
self.i = i
def get(self):
func = getattr(MyClass, 'function{}'.format(self.i))
func(self, 12) # This one will work
# self.func(12) # But this does NOT work.
def function1(self, p1):
print('function1: {}'.format(p1))
# do other stuff
def function2(self, p1):
print('function2: {}'.format(p1))
# do other stuff
if __name__ == "__main__":
class1 = MyClass(1)
class1.get()
class2 = MyClass(2)
class2.get()
Output (Python 3.7.x)
function1: 12
function2: 12
none of what was suggested helped me. I did discover this though.
<object>.__getattribute__(<string name>)(<params>)
I am using python 2.66
Hope this helps
Although getattr() is elegant (and about 7x faster) method, you can get return value from the function (local, class method, module) with eval as elegant as x = eval('foo.bar')(). And when you implement some error handling then quite securely (the same principle can be used for getattr). Example with module import and class:
# import module, call module function, pass parameters and print retured value with eval():
import random
bar = 'random.randint'
randint = eval(bar)(0,100)
print(randint) # will print random int from <0;100)
# also class method returning (or not) value(s) can be used with eval:
class Say:
def say(something='nothing'):
return something
bar = 'Say.say'
print(eval(bar)('nice to meet you too')) # will print 'nice to meet you'
When module or class does not exist (typo or anything better) then NameError is raised. When function does not exist, then AttributeError is raised. This can be used to handle errors:
# try/except block can be used to catch both errors
try:
eval('Say.talk')() # raises AttributeError because function does not exist
eval('Says.say')() # raises NameError because the class does not exist
# or the same with getattr:
getattr(Say, 'talk')() # raises AttributeError
getattr(Says, 'say')() # raises NameError
except AttributeError:
# do domething or just...
print('Function does not exist')
except NameError:
# do domething or just...
print('Module does not exist')
In python3, you can use the __getattribute__ method. See following example with a list method name string:
func_name = 'reverse'
l = [1, 2, 3, 4]
print(l)
>> [1, 2, 3, 4]
l.__getattribute__(func_name)()
print(l)
>> [4, 3, 2, 1]
Nobody mentioned operator.attrgetter yet:
>>> from operator import attrgetter
>>> l = [1, 2, 3]
>>> attrgetter('reverse')(l)()
>>> l
[3, 2, 1]
>>>
getattr calls method by name from an object.
But this object should be parent of calling class.
The parent class can be got by super(self.__class__, self)
class Base:
def call_base(func):
"""This does not work"""
def new_func(self, *args, **kwargs):
name = func.__name__
getattr(super(self.__class__, self), name)(*args, **kwargs)
return new_func
def f(self, *args):
print(f"BASE method invoked.")
def g(self, *args):
print(f"BASE method invoked.")
class Inherit(Base):
#Base.call_base
def f(self, *args):
"""function body will be ignored by the decorator."""
pass
#Base.call_base
def g(self, *args):
"""function body will be ignored by the decorator."""
pass
Inherit().f() # The goal is to print "BASE method invoked."
i'm facing the similar problem before, which is to convert a string to a function. but i can't use eval() or ast.literal_eval(), because i don't want to execute this code immediately.
e.g. i have a string "foo.bar", and i want to assign it to x as a function name instead of a string, which means i can call the function by x() ON DEMAND.
here's my code:
str_to_convert = "foo.bar"
exec(f"x = {str_to_convert}")
x()
as for your question, you only need to add your module name foo and . before {} as follows:
str_to_convert = "bar"
exec(f"x = foo.{str_to_convert}")
x()
WARNING!!! either eval() or exec() is a dangerous method, you should confirm the safety.
WARNING!!! either eval() or exec() is a dangerous method, you should confirm the safety.
WARNING!!! either eval() or exec() is a dangerous method, you should confirm the safety.
You means get the pointer to an inner function from a module
import foo
method = foo.bar
executed = method(parameter)
This is not a better pythonic way indeed is possible for punctual cases
This is a simple answer, this will allow you to clear the screen for example. There are two examples below, with eval and exec, that will print 0 at the top after cleaning (if you're using Windows, change clear to cls, Linux and Mac users leave as is for example) or just execute it, respectively.
eval("os.system(\"clear\")")
exec("os.system(\"clear\")")

Categories