How to call a function using dictionary key Value? [duplicate] - python

This question already has answers here:
Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function?
(3 answers)
Closed 4 years ago.
Here I am trying to call a function using dictionary key value.
>>> def hello():
print('hello')
>>> a = {'+': hello()}
it just prints hello after executing this line.
>>> a['+']
If I call the dictionary using key value, it results nothing. What am I missing here?

Do not put () while you are using the function name as a value for the dictionary because as soon as python find () it will execute the function.
Instead just add the function name a = {'+': hello}
And then use the () while fetching the value from the dictionary
a["+"]()

You need a return call.
def hello():
return 'hello'
Or I think that is what you want

You should put your callable as the value into the dict and then call it.
>>> def hello():
print('hello')
>>> a = {'+': hello}
>>> a['+']()
hello

Related

Converting List of Strings into List of Callable Functions in Python [duplicate]

This question already has answers here:
Call a function from a stored string in Python [duplicate]
(4 answers)
Closed 1 year ago.
I have scraped some strings from emails into a list. The strings correspond to the names of functions which I want to be able to call later. I cannot call them in their current form so is there a way of converting the list of strings into a list of functions that I can call?
For example:
a = ['SU', 'BT', 'PL']
str = 'sdf sghf sdfgdf SU agffg BL asu'
matches = [x for x in a if x in str]
print(matches)
returns:
['SU', 'BL']
But I cannot call functions SU and BL from this list given the format.
With this example:
def my_func1():
print("ONE")
def my_func2():
print("TWO")
You can try eval, but it's not a good practise: (explanation)
eval("my_func1")()
Or you can assign this function to a string equivalent (inside a dictionary), and run that:
my_func_dict = {
"my_func1": my_func1,
"my_func2": my_func2
}
my_func_dict["my_func1"]()
Both of these examples will print ONE.
Or closer to your example:
a = [my_func1, my_func2]
matches = [x for x in a if x.__name__ in str]
# matches now has two funcions inside, so you can run either:
matches[0]()
matches[1]()

Do stuff with variable that has the same name of a string [duplicate]

This question already has answers here:
How to use string value as a variable name in Python? [duplicate]
(3 answers)
How do I create variable variables?
(17 answers)
Closed 4 years ago.
let's say I have a variable called "x" and a string that has the value of "x" (string1 = "x"). How do I do stuff with the variable through the string?
For example change the variable's value or call a method if it's an object?
Thanks in advance
Variables are available through dictionaries locals() and globals(). If you want to access a particular variable by it's spring name, you can do e.g.
>>> my_var = 'hello'
>>> x = 'my_var'
>>> locals()[x]
'hello'
You can also assign back to the variable using this approach, e.g.
>>> my_var = 'hello'
>>> x = 'my_var'
>>> locals()[x] = 'something else'
>>> my_var
'something else'
Since functions are objects in Python, you can access any locally available functions in the same manner to call them.
>>> def my_test_function(n):
>>> return n*8
Accessing the method and calling it.
>>> locals()['my_test_function'](4)
32
For accessing attributes of objects by their name you can use getattr(), and setattr() to set them. For example, creating an object with a single property called your_prop.
class Example:
your_prop = 2
a = Example()
The value is available via your_prop.
>>> a.your_prop
2
The property can be accessed via name using getattr
>>> getattr(a, 'your_prop')
2
The property can be set using setattr:
>>> setattr(a, 'your_prop', 5)
>>> a.your_prop
5
Ok, let's suppose that you have lots of different functions: Aoo(), Boo(), Coo()... and let's suppose that you want to specify which of them to call via command line argument.
Now, that argument will be a string, so you need to call a function through its name, but you do not know in advance the name of the function.
One possible solution is to use exec():
def boo():
print("boo function")
def coo():
print("coo function")
Now:
argument = "boo"
exec(argument + "()")
>>> boo function
and
argument = "coo"
exec(argument + "()")
>>> coo function
It depends what you're trying to do, but you can scoop up whatever x is pointing to with locals() or globals():
def x(k):
return k + 1
string1 = "x"
the_function_x = locals()[string1]
print(the_function_x(3))
outputs 4 (it called the x function by utilizing string1).

NoneType occuring when I run my code [duplicate]

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 5 years ago.
Why does this code return None?
def html_list(inputs_list):
print("<ul>")
for html in inputs_list:
html = ("<li>" + html + "</li>")
print(html)
print("</ul>")
bam = ['boom','bust']
print(html_list(bam))
Your function has print calls within it, but does not return anything. If a function completes without returning, it really returns None.
This means that if you call the function inside a print statement, it will run, do the prints within the function, but return None which will then get passed into the print() function - so this is why you get the intended output and then a "None" at the end.
You can also see this through a more simple example:
>>> def f():
... print("inside f")
...
>>> print(f())
inside f
None

Construct callable function from string [duplicate]

This question already has answers here:
Calling a function of a module by using its name (a string)
(18 answers)
Closed 5 years ago.
How to construct and call a function from a string?
For example, consider three different functions and a list of strings, I want to be able to use the items in list of strings to construct and call the appropriate function
def do_function1():
return 'done function1'
def do_function2():
return 'done function2'
def do_function3():
return 'done function3'
listOfstr = ['function1','function2','function3']
for item in listOfstr:
result = 'do_'+item()
print(result)
result = 'do_'+item()
TypeError: 'str' object is not callable
The problematic code is
listOfstr = ['function1','function2','function3']
for item in listOfstr:
result = 'do_'+item()
In the first loop item, will have the value 'function1'. You are calling this string as if it were a function. But strings are not callable and have no code assigned to them!
Then, you go on with the for loop before doing anything.
Simply refer to item, like this:
for item in listOfstr:
func_name = 'do_' + item
func = globals()[func_name]
func()
The most explicit way would be to have a dictionary of those functions:
funcs = {
'function1': do_function1,
'function2': do_function2,
'function3': do_function3,
}
funcs[item]()
That way you can also name your functions whatever you want, decouple from item names, make them methods, move to other modules etc without breaking the general design. The other way is globals, as already answered.
First of all, usually you won't need this. Instead of putting strings in a list, you can also put functions themselves in a list like this:
def do_function1():
return 'done function1'
def do_function2():
return 'done function2'
def do_function3():
return 'done function3'
list_of_functions = [do_function1, do_function2, do_function3]
for item in list_of_functions:
result = item()
print(result)
However, if you insist, you can do it like this:
locals()["do_function1"]()
locals() gives you a dictionary of locally defined objects by name.

python select a function based on the value in a dictionary [duplicate]

This question already has answers here:
Calling a function of a module by using its name (a string)
(18 answers)
Closed 6 years ago.
I want to select a function based on the value of a dictionary:
dict = {"func_selector":"func1", "param_value":"some_value"}
# defined a function
def func1(param):
# some function code
Now, I want to select the function based on the value of some key, so that it can achieve something like:
# calling a function based on some dict value
dict["func_selector"](dict["param_value"])
The syntax is probably wrong, but I am wondering if it is possible to do that in Python or something similar.
Try storing the value of the function in the dictionary, instead of its name:
def func1(param):
print "func1, param=%r" % (param,)
d = {"func_selector":func1, "param_value": "some value"}
Then you can say:
>>> d['func_selector'](d['param_value'])
func1, param='some value'
The best approach IMO is do it like this
def func1(param):
#code
some_value = ... #The value you need
my_dict = {"func_selector": func1, "param_value": some_value }
And then
my_dict["func_selector"](my_dict["param_value"])
Now, if you only have the name of the function you need to call getattr
And call it
getattr(my_class, my_dict["func_selector"])(my_dict["param_value"])
my_class is the class which contains the method. If it's not in a class I think you can pass self

Categories

Resources