Calling a function of a module by using its name (a string)
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module foo
, and I have a string whose content is "bar"
. What is the best way to call foo.bar()
?
I need to get the return value of the function, which is why I don't just use eval
. I figured out how to do it by using eval
to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
python object
add a comment |
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module foo
, and I have a string whose content is "bar"
. What is the best way to call foo.bar()
?
I need to get the return value of the function, which is why I don't just use eval
. I figured out how to do it by using eval
to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
python object
add a comment |
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module foo
, and I have a string whose content is "bar"
. What is the best way to call foo.bar()
?
I need to get the return value of the function, which is why I don't just use eval
. I figured out how to do it by using eval
to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
python object
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module foo
, and I have a string whose content is "bar"
. What is the best way to call foo.bar()
?
I need to get the return value of the function, which is why I don't just use eval
. I figured out how to do it by using eval
to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
python object
python object
edited Jan 23 at 15:03
Tommy Herbert
10.4k124151
10.4k124151
asked Aug 6 '08 at 3:36
ricreericree
11.9k133027
11.9k133027
add a comment |
add a comment |
11 Answers
11
active
oldest
votes
Assuming module foo
with method bar
:
import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()
As far as that goes, lines 2 and 3 can be compressed to:
result = getattr(foo, 'bar')()
if that makes more sense for your use case. You can use getattr
in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.
5
hasattr or getattr can be used to determine if a function is defined. I had a database mapping (eventType and handling functionName) and I wanted to make sure I never "forgot" to define an event handler in my python
– Shaun
Jun 3 '14 at 13:20
5
This works if you already know the module name. However, if you want the user to provide the module name as a string, this won't work.
– Blairg23
Jun 21 '14 at 7:39
5
If you need to avoid a NoneType is not callable exception, you could also employ the three-argument form of getattr: getattr(foo, 'bar', lambda: None). I apologize for the formatting; the stackexchange android app is apparently terrible.
– geekofalltrades
Aug 16 '14 at 18:01
3
See also the answer provided by @sastanin if you only care for example about your local/current module's functions.
– NuSkooler
Jun 19 '15 at 22:19
2
@Janefoo
isn't a real module here, it is a placeholder for any module. Sorry for the confusion. I would consider editing the answer to use a real module, but it's been so heavily up-voted I'm not sure I should at this point.
– Patrick Johnmeyer
Jul 17 '18 at 19:54
|
show 12 more comments
locals()["myfunction"]()
or
globals()["myfunction"]()
locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.
36
This method with globals/locals is good if the method you need to call is defined in the same module you are calling from.
– Joelmob
Oct 9 '14 at 21:36
@Joelmob is there any other way to get an object by string out of the root namespace?
– Nick T
Jan 26 '15 at 20:51
@NickT I am only aware of these methods, I don't think there are any others that fill same function as these, at least I can't think of a reason why there should be more.
– Joelmob
Jan 27 '15 at 12:34
I've got a reason for you (actually what led me here): Module A has a function F that needs to call a function by name. Module B imports Module A, and invokes function F with a request to call Function G, which is defined in Module B. This call fails because, apparently, function F only runs with the globals that are defined in Module F - so globals()['G'] = None.
– David Stein
Jan 30 '17 at 15:18
add a comment |
Patrick's solution is probably the cleanest.
If you need to dynamically pick up the module as well, you can import it like:
module = __import__('foo')
func = getattr(module, 'bar')
func()
83
I do not understand that last comment. __import__ has its own right and the next sentence in the mentioned docs says: "Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime". So: +1 for the given answer.
– hoffmaje
May 5 '12 at 9:33
43
Useimportlib.import_module
. The official docs say about__import__
: "This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module()." docs.python.org/2/library/functions.html#__import__
– glarrain
Aug 5 '13 at 22:07
8
@glarrain As long as you're ok with only support 2.7 and up.
– Xiong Chiamiov
Sep 14 '13 at 16:54
@Xiong Chaimiov,importlib.import_module
is supported in 3.6 . See docs.python.org/3.6/library/…
– cowlinator
Oct 5 '17 at 19:28
7
@cowlinator Yes, 3.6 is part of "2.7 and up", both in strict versioning semantics and in release dates (it came about six years later). It also didn't exist for three years after my comment. ;) In the 3.x branch, the module has been around since 3.1. 2.7 and 3.1 are now pretty ancient; you'll still find servers hanging around that only support 2.6, but it's probably worth having importlib be the standard advice nowadays.
– Xiong Chiamiov
Oct 5 '17 at 23:55
|
show 1 more comment
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')
add a comment |
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()
This helped me. Its a lightweight version of__import__
function.
– Pankaj Bhambhani
Dec 16 '15 at 13:19
add a comment |
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
add a comment |
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")()
add a comment |
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)
Just a bit more generic ishandler = getattr(sys.modules[__name__], myFnName)
– lony
Oct 6 '17 at 12:33
add a comment |
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)
1
This would be risky. string can have anything and eval would end up eval-ling it without any consideration.
– iankit
Dec 30 '16 at 18:13
2
Sure, you must be mindful of the context you are using it in, whether this will be appropriate or not, given those risks.
– tvt173
Jan 6 '17 at 18:48
1
A function should not be responsible for validating it's parameters - that's the job of a different function. Saying that it's risky to use eval with a string is saying that use of every function is risky.
– red777
Aug 14 '18 at 11:01
You should never useeval
unless strictly necessary.getattr(__module__, method_name)
is a much better choice in this context.
– moi
Jan 14 at 12:05
add a comment |
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
10
In what aspect is this better than getattr() ?
– V13
Jul 29 '16 at 12:26
1
Exactly what i wanted. Works like a charm! Perfect!!self.__getattribute__('title')
is equal toself.title
– ioaniatr
Aug 6 '18 at 18:49
self.__getattribute__('title')
doesn't work in any cases(don't know why) afterall, butfunc = getattr(self, 'title'); func();
does. So, maybe is better to usegetattr()
instead
– ioaniatr
Aug 16 '18 at 16:52
5
Can people who don't know python please stop upvoting this junk? Usegetattr
instead.
– Aran-Fey
Oct 23 '18 at 5:19
add a comment |
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
add a comment |
protected by Bo Persson Jan 6 '13 at 23:06
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
11 Answers
11
active
oldest
votes
11 Answers
11
active
oldest
votes
active
oldest
votes
active
oldest
votes
Assuming module foo
with method bar
:
import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()
As far as that goes, lines 2 and 3 can be compressed to:
result = getattr(foo, 'bar')()
if that makes more sense for your use case. You can use getattr
in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.
5
hasattr or getattr can be used to determine if a function is defined. I had a database mapping (eventType and handling functionName) and I wanted to make sure I never "forgot" to define an event handler in my python
– Shaun
Jun 3 '14 at 13:20
5
This works if you already know the module name. However, if you want the user to provide the module name as a string, this won't work.
– Blairg23
Jun 21 '14 at 7:39
5
If you need to avoid a NoneType is not callable exception, you could also employ the three-argument form of getattr: getattr(foo, 'bar', lambda: None). I apologize for the formatting; the stackexchange android app is apparently terrible.
– geekofalltrades
Aug 16 '14 at 18:01
3
See also the answer provided by @sastanin if you only care for example about your local/current module's functions.
– NuSkooler
Jun 19 '15 at 22:19
2
@Janefoo
isn't a real module here, it is a placeholder for any module. Sorry for the confusion. I would consider editing the answer to use a real module, but it's been so heavily up-voted I'm not sure I should at this point.
– Patrick Johnmeyer
Jul 17 '18 at 19:54
|
show 12 more comments
Assuming module foo
with method bar
:
import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()
As far as that goes, lines 2 and 3 can be compressed to:
result = getattr(foo, 'bar')()
if that makes more sense for your use case. You can use getattr
in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.
5
hasattr or getattr can be used to determine if a function is defined. I had a database mapping (eventType and handling functionName) and I wanted to make sure I never "forgot" to define an event handler in my python
– Shaun
Jun 3 '14 at 13:20
5
This works if you already know the module name. However, if you want the user to provide the module name as a string, this won't work.
– Blairg23
Jun 21 '14 at 7:39
5
If you need to avoid a NoneType is not callable exception, you could also employ the three-argument form of getattr: getattr(foo, 'bar', lambda: None). I apologize for the formatting; the stackexchange android app is apparently terrible.
– geekofalltrades
Aug 16 '14 at 18:01
3
See also the answer provided by @sastanin if you only care for example about your local/current module's functions.
– NuSkooler
Jun 19 '15 at 22:19
2
@Janefoo
isn't a real module here, it is a placeholder for any module. Sorry for the confusion. I would consider editing the answer to use a real module, but it's been so heavily up-voted I'm not sure I should at this point.
– Patrick Johnmeyer
Jul 17 '18 at 19:54
|
show 12 more comments
Assuming module foo
with method bar
:
import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()
As far as that goes, lines 2 and 3 can be compressed to:
result = getattr(foo, 'bar')()
if that makes more sense for your use case. You can use getattr
in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.
Assuming module foo
with method bar
:
import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()
As far as that goes, lines 2 and 3 can be compressed to:
result = getattr(foo, 'bar')()
if that makes more sense for your use case. You can use getattr
in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.
edited Feb 22 '17 at 18:10
Ben Hoyt
6,35144276
6,35144276
answered Aug 6 '08 at 3:57
Patrick JohnmeyerPatrick Johnmeyer
19k22023
19k22023
5
hasattr or getattr can be used to determine if a function is defined. I had a database mapping (eventType and handling functionName) and I wanted to make sure I never "forgot" to define an event handler in my python
– Shaun
Jun 3 '14 at 13:20
5
This works if you already know the module name. However, if you want the user to provide the module name as a string, this won't work.
– Blairg23
Jun 21 '14 at 7:39
5
If you need to avoid a NoneType is not callable exception, you could also employ the three-argument form of getattr: getattr(foo, 'bar', lambda: None). I apologize for the formatting; the stackexchange android app is apparently terrible.
– geekofalltrades
Aug 16 '14 at 18:01
3
See also the answer provided by @sastanin if you only care for example about your local/current module's functions.
– NuSkooler
Jun 19 '15 at 22:19
2
@Janefoo
isn't a real module here, it is a placeholder for any module. Sorry for the confusion. I would consider editing the answer to use a real module, but it's been so heavily up-voted I'm not sure I should at this point.
– Patrick Johnmeyer
Jul 17 '18 at 19:54
|
show 12 more comments
5
hasattr or getattr can be used to determine if a function is defined. I had a database mapping (eventType and handling functionName) and I wanted to make sure I never "forgot" to define an event handler in my python
– Shaun
Jun 3 '14 at 13:20
5
This works if you already know the module name. However, if you want the user to provide the module name as a string, this won't work.
– Blairg23
Jun 21 '14 at 7:39
5
If you need to avoid a NoneType is not callable exception, you could also employ the three-argument form of getattr: getattr(foo, 'bar', lambda: None). I apologize for the formatting; the stackexchange android app is apparently terrible.
– geekofalltrades
Aug 16 '14 at 18:01
3
See also the answer provided by @sastanin if you only care for example about your local/current module's functions.
– NuSkooler
Jun 19 '15 at 22:19
2
@Janefoo
isn't a real module here, it is a placeholder for any module. Sorry for the confusion. I would consider editing the answer to use a real module, but it's been so heavily up-voted I'm not sure I should at this point.
– Patrick Johnmeyer
Jul 17 '18 at 19:54
5
5
hasattr or getattr can be used to determine if a function is defined. I had a database mapping (eventType and handling functionName) and I wanted to make sure I never "forgot" to define an event handler in my python
– Shaun
Jun 3 '14 at 13:20
hasattr or getattr can be used to determine if a function is defined. I had a database mapping (eventType and handling functionName) and I wanted to make sure I never "forgot" to define an event handler in my python
– Shaun
Jun 3 '14 at 13:20
5
5
This works if you already know the module name. However, if you want the user to provide the module name as a string, this won't work.
– Blairg23
Jun 21 '14 at 7:39
This works if you already know the module name. However, if you want the user to provide the module name as a string, this won't work.
– Blairg23
Jun 21 '14 at 7:39
5
5
If you need to avoid a NoneType is not callable exception, you could also employ the three-argument form of getattr: getattr(foo, 'bar', lambda: None). I apologize for the formatting; the stackexchange android app is apparently terrible.
– geekofalltrades
Aug 16 '14 at 18:01
If you need to avoid a NoneType is not callable exception, you could also employ the three-argument form of getattr: getattr(foo, 'bar', lambda: None). I apologize for the formatting; the stackexchange android app is apparently terrible.
– geekofalltrades
Aug 16 '14 at 18:01
3
3
See also the answer provided by @sastanin if you only care for example about your local/current module's functions.
– NuSkooler
Jun 19 '15 at 22:19
See also the answer provided by @sastanin if you only care for example about your local/current module's functions.
– NuSkooler
Jun 19 '15 at 22:19
2
2
@Jane
foo
isn't a real module here, it is a placeholder for any module. Sorry for the confusion. I would consider editing the answer to use a real module, but it's been so heavily up-voted I'm not sure I should at this point.– Patrick Johnmeyer
Jul 17 '18 at 19:54
@Jane
foo
isn't a real module here, it is a placeholder for any module. Sorry for the confusion. I would consider editing the answer to use a real module, but it's been so heavily up-voted I'm not sure I should at this point.– Patrick Johnmeyer
Jul 17 '18 at 19:54
|
show 12 more comments
locals()["myfunction"]()
or
globals()["myfunction"]()
locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.
36
This method with globals/locals is good if the method you need to call is defined in the same module you are calling from.
– Joelmob
Oct 9 '14 at 21:36
@Joelmob is there any other way to get an object by string out of the root namespace?
– Nick T
Jan 26 '15 at 20:51
@NickT I am only aware of these methods, I don't think there are any others that fill same function as these, at least I can't think of a reason why there should be more.
– Joelmob
Jan 27 '15 at 12:34
I've got a reason for you (actually what led me here): Module A has a function F that needs to call a function by name. Module B imports Module A, and invokes function F with a request to call Function G, which is defined in Module B. This call fails because, apparently, function F only runs with the globals that are defined in Module F - so globals()['G'] = None.
– David Stein
Jan 30 '17 at 15:18
add a comment |
locals()["myfunction"]()
or
globals()["myfunction"]()
locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.
36
This method with globals/locals is good if the method you need to call is defined in the same module you are calling from.
– Joelmob
Oct 9 '14 at 21:36
@Joelmob is there any other way to get an object by string out of the root namespace?
– Nick T
Jan 26 '15 at 20:51
@NickT I am only aware of these methods, I don't think there are any others that fill same function as these, at least I can't think of a reason why there should be more.
– Joelmob
Jan 27 '15 at 12:34
I've got a reason for you (actually what led me here): Module A has a function F that needs to call a function by name. Module B imports Module A, and invokes function F with a request to call Function G, which is defined in Module B. This call fails because, apparently, function F only runs with the globals that are defined in Module F - so globals()['G'] = None.
– David Stein
Jan 30 '17 at 15:18
add a comment |
locals()["myfunction"]()
or
globals()["myfunction"]()
locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.
locals()["myfunction"]()
or
globals()["myfunction"]()
locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.
answered May 7 '09 at 12:45
sastaninsastanin
28.1k984125
28.1k984125
36
This method with globals/locals is good if the method you need to call is defined in the same module you are calling from.
– Joelmob
Oct 9 '14 at 21:36
@Joelmob is there any other way to get an object by string out of the root namespace?
– Nick T
Jan 26 '15 at 20:51
@NickT I am only aware of these methods, I don't think there are any others that fill same function as these, at least I can't think of a reason why there should be more.
– Joelmob
Jan 27 '15 at 12:34
I've got a reason for you (actually what led me here): Module A has a function F that needs to call a function by name. Module B imports Module A, and invokes function F with a request to call Function G, which is defined in Module B. This call fails because, apparently, function F only runs with the globals that are defined in Module F - so globals()['G'] = None.
– David Stein
Jan 30 '17 at 15:18
add a comment |
36
This method with globals/locals is good if the method you need to call is defined in the same module you are calling from.
– Joelmob
Oct 9 '14 at 21:36
@Joelmob is there any other way to get an object by string out of the root namespace?
– Nick T
Jan 26 '15 at 20:51
@NickT I am only aware of these methods, I don't think there are any others that fill same function as these, at least I can't think of a reason why there should be more.
– Joelmob
Jan 27 '15 at 12:34
I've got a reason for you (actually what led me here): Module A has a function F that needs to call a function by name. Module B imports Module A, and invokes function F with a request to call Function G, which is defined in Module B. This call fails because, apparently, function F only runs with the globals that are defined in Module F - so globals()['G'] = None.
– David Stein
Jan 30 '17 at 15:18
36
36
This method with globals/locals is good if the method you need to call is defined in the same module you are calling from.
– Joelmob
Oct 9 '14 at 21:36
This method with globals/locals is good if the method you need to call is defined in the same module you are calling from.
– Joelmob
Oct 9 '14 at 21:36
@Joelmob is there any other way to get an object by string out of the root namespace?
– Nick T
Jan 26 '15 at 20:51
@Joelmob is there any other way to get an object by string out of the root namespace?
– Nick T
Jan 26 '15 at 20:51
@NickT I am only aware of these methods, I don't think there are any others that fill same function as these, at least I can't think of a reason why there should be more.
– Joelmob
Jan 27 '15 at 12:34
@NickT I am only aware of these methods, I don't think there are any others that fill same function as these, at least I can't think of a reason why there should be more.
– Joelmob
Jan 27 '15 at 12:34
I've got a reason for you (actually what led me here): Module A has a function F that needs to call a function by name. Module B imports Module A, and invokes function F with a request to call Function G, which is defined in Module B. This call fails because, apparently, function F only runs with the globals that are defined in Module F - so globals()['G'] = None.
– David Stein
Jan 30 '17 at 15:18
I've got a reason for you (actually what led me here): Module A has a function F that needs to call a function by name. Module B imports Module A, and invokes function F with a request to call Function G, which is defined in Module B. This call fails because, apparently, function F only runs with the globals that are defined in Module F - so globals()['G'] = None.
– David Stein
Jan 30 '17 at 15:18
add a comment |
Patrick's solution is probably the cleanest.
If you need to dynamically pick up the module as well, you can import it like:
module = __import__('foo')
func = getattr(module, 'bar')
func()
83
I do not understand that last comment. __import__ has its own right and the next sentence in the mentioned docs says: "Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime". So: +1 for the given answer.
– hoffmaje
May 5 '12 at 9:33
43
Useimportlib.import_module
. The official docs say about__import__
: "This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module()." docs.python.org/2/library/functions.html#__import__
– glarrain
Aug 5 '13 at 22:07
8
@glarrain As long as you're ok with only support 2.7 and up.
– Xiong Chiamiov
Sep 14 '13 at 16:54
@Xiong Chaimiov,importlib.import_module
is supported in 3.6 . See docs.python.org/3.6/library/…
– cowlinator
Oct 5 '17 at 19:28
7
@cowlinator Yes, 3.6 is part of "2.7 and up", both in strict versioning semantics and in release dates (it came about six years later). It also didn't exist for three years after my comment. ;) In the 3.x branch, the module has been around since 3.1. 2.7 and 3.1 are now pretty ancient; you'll still find servers hanging around that only support 2.6, but it's probably worth having importlib be the standard advice nowadays.
– Xiong Chiamiov
Oct 5 '17 at 23:55
|
show 1 more comment
Patrick's solution is probably the cleanest.
If you need to dynamically pick up the module as well, you can import it like:
module = __import__('foo')
func = getattr(module, 'bar')
func()
83
I do not understand that last comment. __import__ has its own right and the next sentence in the mentioned docs says: "Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime". So: +1 for the given answer.
– hoffmaje
May 5 '12 at 9:33
43
Useimportlib.import_module
. The official docs say about__import__
: "This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module()." docs.python.org/2/library/functions.html#__import__
– glarrain
Aug 5 '13 at 22:07
8
@glarrain As long as you're ok with only support 2.7 and up.
– Xiong Chiamiov
Sep 14 '13 at 16:54
@Xiong Chaimiov,importlib.import_module
is supported in 3.6 . See docs.python.org/3.6/library/…
– cowlinator
Oct 5 '17 at 19:28
7
@cowlinator Yes, 3.6 is part of "2.7 and up", both in strict versioning semantics and in release dates (it came about six years later). It also didn't exist for three years after my comment. ;) In the 3.x branch, the module has been around since 3.1. 2.7 and 3.1 are now pretty ancient; you'll still find servers hanging around that only support 2.6, but it's probably worth having importlib be the standard advice nowadays.
– Xiong Chiamiov
Oct 5 '17 at 23:55
|
show 1 more comment
Patrick's solution is probably the cleanest.
If you need to dynamically pick up the module as well, you can import it like:
module = __import__('foo')
func = getattr(module, 'bar')
func()
Patrick's solution is probably the cleanest.
If you need to dynamically pick up the module as well, you can import it like:
module = __import__('foo')
func = getattr(module, 'bar')
func()
edited Feb 22 '17 at 18:08
Ben Hoyt
6,35144276
6,35144276
answered Aug 7 '08 at 11:35
HS.HS.
10.9k73346
10.9k73346
83
I do not understand that last comment. __import__ has its own right and the next sentence in the mentioned docs says: "Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime". So: +1 for the given answer.
– hoffmaje
May 5 '12 at 9:33
43
Useimportlib.import_module
. The official docs say about__import__
: "This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module()." docs.python.org/2/library/functions.html#__import__
– glarrain
Aug 5 '13 at 22:07
8
@glarrain As long as you're ok with only support 2.7 and up.
– Xiong Chiamiov
Sep 14 '13 at 16:54
@Xiong Chaimiov,importlib.import_module
is supported in 3.6 . See docs.python.org/3.6/library/…
– cowlinator
Oct 5 '17 at 19:28
7
@cowlinator Yes, 3.6 is part of "2.7 and up", both in strict versioning semantics and in release dates (it came about six years later). It also didn't exist for three years after my comment. ;) In the 3.x branch, the module has been around since 3.1. 2.7 and 3.1 are now pretty ancient; you'll still find servers hanging around that only support 2.6, but it's probably worth having importlib be the standard advice nowadays.
– Xiong Chiamiov
Oct 5 '17 at 23:55
|
show 1 more comment
83
I do not understand that last comment. __import__ has its own right and the next sentence in the mentioned docs says: "Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime". So: +1 for the given answer.
– hoffmaje
May 5 '12 at 9:33
43
Useimportlib.import_module
. The official docs say about__import__
: "This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module()." docs.python.org/2/library/functions.html#__import__
– glarrain
Aug 5 '13 at 22:07
8
@glarrain As long as you're ok with only support 2.7 and up.
– Xiong Chiamiov
Sep 14 '13 at 16:54
@Xiong Chaimiov,importlib.import_module
is supported in 3.6 . See docs.python.org/3.6/library/…
– cowlinator
Oct 5 '17 at 19:28
7
@cowlinator Yes, 3.6 is part of "2.7 and up", both in strict versioning semantics and in release dates (it came about six years later). It also didn't exist for three years after my comment. ;) In the 3.x branch, the module has been around since 3.1. 2.7 and 3.1 are now pretty ancient; you'll still find servers hanging around that only support 2.6, but it's probably worth having importlib be the standard advice nowadays.
– Xiong Chiamiov
Oct 5 '17 at 23:55
83
83
I do not understand that last comment. __import__ has its own right and the next sentence in the mentioned docs says: "Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime". So: +1 for the given answer.
– hoffmaje
May 5 '12 at 9:33
I do not understand that last comment. __import__ has its own right and the next sentence in the mentioned docs says: "Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime". So: +1 for the given answer.
– hoffmaje
May 5 '12 at 9:33
43
43
Use
importlib.import_module
. The official docs say about __import__
: "This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module()." docs.python.org/2/library/functions.html#__import__– glarrain
Aug 5 '13 at 22:07
Use
importlib.import_module
. The official docs say about __import__
: "This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module()." docs.python.org/2/library/functions.html#__import__– glarrain
Aug 5 '13 at 22:07
8
8
@glarrain As long as you're ok with only support 2.7 and up.
– Xiong Chiamiov
Sep 14 '13 at 16:54
@glarrain As long as you're ok with only support 2.7 and up.
– Xiong Chiamiov
Sep 14 '13 at 16:54
@Xiong Chaimiov,
importlib.import_module
is supported in 3.6 . See docs.python.org/3.6/library/…– cowlinator
Oct 5 '17 at 19:28
@Xiong Chaimiov,
importlib.import_module
is supported in 3.6 . See docs.python.org/3.6/library/…– cowlinator
Oct 5 '17 at 19:28
7
7
@cowlinator Yes, 3.6 is part of "2.7 and up", both in strict versioning semantics and in release dates (it came about six years later). It also didn't exist for three years after my comment. ;) In the 3.x branch, the module has been around since 3.1. 2.7 and 3.1 are now pretty ancient; you'll still find servers hanging around that only support 2.6, but it's probably worth having importlib be the standard advice nowadays.
– Xiong Chiamiov
Oct 5 '17 at 23:55
@cowlinator Yes, 3.6 is part of "2.7 and up", both in strict versioning semantics and in release dates (it came about six years later). It also didn't exist for three years after my comment. ;) In the 3.x branch, the module has been around since 3.1. 2.7 and 3.1 are now pretty ancient; you'll still find servers hanging around that only support 2.6, but it's probably worth having importlib be the standard advice nowadays.
– Xiong Chiamiov
Oct 5 '17 at 23:55
|
show 1 more comment
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')
add a comment |
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')
add a comment |
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')
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')
edited Sep 22 '14 at 21:49
tbc0
8611016
8611016
answered Aug 19 '12 at 9:40
SourcegeekSourcegeek
93962
93962
add a comment |
add a comment |
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()
This helped me. Its a lightweight version of__import__
function.
– Pankaj Bhambhani
Dec 16 '15 at 13:19
add a comment |
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()
This helped me. Its a lightweight version of__import__
function.
– Pankaj Bhambhani
Dec 16 '15 at 13:19
add a comment |
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()
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()
answered Oct 16 '13 at 0:24
ferrouswheelferrouswheel
2,2741822
2,2741822
This helped me. Its a lightweight version of__import__
function.
– Pankaj Bhambhani
Dec 16 '15 at 13:19
add a comment |
This helped me. Its a lightweight version of__import__
function.
– Pankaj Bhambhani
Dec 16 '15 at 13:19
This helped me. Its a lightweight version of
__import__
function.– Pankaj Bhambhani
Dec 16 '15 at 13:19
This helped me. Its a lightweight version of
__import__
function.– Pankaj Bhambhani
Dec 16 '15 at 13:19
add a comment |
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
add a comment |
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
add a comment |
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 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
answered Oct 24 '16 at 13:20
user3946687
add a comment |
add a comment |
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")()
add a comment |
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")()
add a comment |
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")()
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")()
answered Apr 9 '14 at 10:17
0050000500500005
1,92921833
1,92921833
add a comment |
add a comment |
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)
Just a bit more generic ishandler = getattr(sys.modules[__name__], myFnName)
– lony
Oct 6 '17 at 12:33
add a comment |
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)
Just a bit more generic ishandler = getattr(sys.modules[__name__], myFnName)
– lony
Oct 6 '17 at 12:33
add a comment |
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)
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)
answered Feb 14 '12 at 5:55
trubliphonetrubliphone
1,50422336
1,50422336
Just a bit more generic ishandler = getattr(sys.modules[__name__], myFnName)
– lony
Oct 6 '17 at 12:33
add a comment |
Just a bit more generic ishandler = getattr(sys.modules[__name__], myFnName)
– lony
Oct 6 '17 at 12:33
Just a bit more generic is
handler = getattr(sys.modules[__name__], myFnName)
– lony
Oct 6 '17 at 12:33
Just a bit more generic is
handler = getattr(sys.modules[__name__], myFnName)
– lony
Oct 6 '17 at 12:33
add a comment |
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)
1
This would be risky. string can have anything and eval would end up eval-ling it without any consideration.
– iankit
Dec 30 '16 at 18:13
2
Sure, you must be mindful of the context you are using it in, whether this will be appropriate or not, given those risks.
– tvt173
Jan 6 '17 at 18:48
1
A function should not be responsible for validating it's parameters - that's the job of a different function. Saying that it's risky to use eval with a string is saying that use of every function is risky.
– red777
Aug 14 '18 at 11:01
You should never useeval
unless strictly necessary.getattr(__module__, method_name)
is a much better choice in this context.
– moi
Jan 14 at 12:05
add a comment |
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)
1
This would be risky. string can have anything and eval would end up eval-ling it without any consideration.
– iankit
Dec 30 '16 at 18:13
2
Sure, you must be mindful of the context you are using it in, whether this will be appropriate or not, given those risks.
– tvt173
Jan 6 '17 at 18:48
1
A function should not be responsible for validating it's parameters - that's the job of a different function. Saying that it's risky to use eval with a string is saying that use of every function is risky.
– red777
Aug 14 '18 at 11:01
You should never useeval
unless strictly necessary.getattr(__module__, method_name)
is a much better choice in this context.
– moi
Jan 14 at 12:05
add a comment |
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)
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)
edited Dec 8 '16 at 18:09
answered Dec 7 '16 at 18:29
tvt173tvt173
904916
904916
1
This would be risky. string can have anything and eval would end up eval-ling it without any consideration.
– iankit
Dec 30 '16 at 18:13
2
Sure, you must be mindful of the context you are using it in, whether this will be appropriate or not, given those risks.
– tvt173
Jan 6 '17 at 18:48
1
A function should not be responsible for validating it's parameters - that's the job of a different function. Saying that it's risky to use eval with a string is saying that use of every function is risky.
– red777
Aug 14 '18 at 11:01
You should never useeval
unless strictly necessary.getattr(__module__, method_name)
is a much better choice in this context.
– moi
Jan 14 at 12:05
add a comment |
1
This would be risky. string can have anything and eval would end up eval-ling it without any consideration.
– iankit
Dec 30 '16 at 18:13
2
Sure, you must be mindful of the context you are using it in, whether this will be appropriate or not, given those risks.
– tvt173
Jan 6 '17 at 18:48
1
A function should not be responsible for validating it's parameters - that's the job of a different function. Saying that it's risky to use eval with a string is saying that use of every function is risky.
– red777
Aug 14 '18 at 11:01
You should never useeval
unless strictly necessary.getattr(__module__, method_name)
is a much better choice in this context.
– moi
Jan 14 at 12:05
1
1
This would be risky. string can have anything and eval would end up eval-ling it without any consideration.
– iankit
Dec 30 '16 at 18:13
This would be risky. string can have anything and eval would end up eval-ling it without any consideration.
– iankit
Dec 30 '16 at 18:13
2
2
Sure, you must be mindful of the context you are using it in, whether this will be appropriate or not, given those risks.
– tvt173
Jan 6 '17 at 18:48
Sure, you must be mindful of the context you are using it in, whether this will be appropriate or not, given those risks.
– tvt173
Jan 6 '17 at 18:48
1
1
A function should not be responsible for validating it's parameters - that's the job of a different function. Saying that it's risky to use eval with a string is saying that use of every function is risky.
– red777
Aug 14 '18 at 11:01
A function should not be responsible for validating it's parameters - that's the job of a different function. Saying that it's risky to use eval with a string is saying that use of every function is risky.
– red777
Aug 14 '18 at 11:01
You should never use
eval
unless strictly necessary. getattr(__module__, method_name)
is a much better choice in this context.– moi
Jan 14 at 12:05
You should never use
eval
unless strictly necessary. getattr(__module__, method_name)
is a much better choice in this context.– moi
Jan 14 at 12:05
add a comment |
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
10
In what aspect is this better than getattr() ?
– V13
Jul 29 '16 at 12:26
1
Exactly what i wanted. Works like a charm! Perfect!!self.__getattribute__('title')
is equal toself.title
– ioaniatr
Aug 6 '18 at 18:49
self.__getattribute__('title')
doesn't work in any cases(don't know why) afterall, butfunc = getattr(self, 'title'); func();
does. So, maybe is better to usegetattr()
instead
– ioaniatr
Aug 16 '18 at 16:52
5
Can people who don't know python please stop upvoting this junk? Usegetattr
instead.
– Aran-Fey
Oct 23 '18 at 5:19
add a comment |
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
10
In what aspect is this better than getattr() ?
– V13
Jul 29 '16 at 12:26
1
Exactly what i wanted. Works like a charm! Perfect!!self.__getattribute__('title')
is equal toself.title
– ioaniatr
Aug 6 '18 at 18:49
self.__getattribute__('title')
doesn't work in any cases(don't know why) afterall, butfunc = getattr(self, 'title'); func();
does. So, maybe is better to usegetattr()
instead
– ioaniatr
Aug 16 '18 at 16:52
5
Can people who don't know python please stop upvoting this junk? Usegetattr
instead.
– Aran-Fey
Oct 23 '18 at 5:19
add a comment |
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
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
answered Dec 28 '12 at 16:56
NatdripNatdrip
481416
481416
10
In what aspect is this better than getattr() ?
– V13
Jul 29 '16 at 12:26
1
Exactly what i wanted. Works like a charm! Perfect!!self.__getattribute__('title')
is equal toself.title
– ioaniatr
Aug 6 '18 at 18:49
self.__getattribute__('title')
doesn't work in any cases(don't know why) afterall, butfunc = getattr(self, 'title'); func();
does. So, maybe is better to usegetattr()
instead
– ioaniatr
Aug 16 '18 at 16:52
5
Can people who don't know python please stop upvoting this junk? Usegetattr
instead.
– Aran-Fey
Oct 23 '18 at 5:19
add a comment |
10
In what aspect is this better than getattr() ?
– V13
Jul 29 '16 at 12:26
1
Exactly what i wanted. Works like a charm! Perfect!!self.__getattribute__('title')
is equal toself.title
– ioaniatr
Aug 6 '18 at 18:49
self.__getattribute__('title')
doesn't work in any cases(don't know why) afterall, butfunc = getattr(self, 'title'); func();
does. So, maybe is better to usegetattr()
instead
– ioaniatr
Aug 16 '18 at 16:52
5
Can people who don't know python please stop upvoting this junk? Usegetattr
instead.
– Aran-Fey
Oct 23 '18 at 5:19
10
10
In what aspect is this better than getattr() ?
– V13
Jul 29 '16 at 12:26
In what aspect is this better than getattr() ?
– V13
Jul 29 '16 at 12:26
1
1
Exactly what i wanted. Works like a charm! Perfect!!
self.__getattribute__('title')
is equal to self.title
– ioaniatr
Aug 6 '18 at 18:49
Exactly what i wanted. Works like a charm! Perfect!!
self.__getattribute__('title')
is equal to self.title
– ioaniatr
Aug 6 '18 at 18:49
self.__getattribute__('title')
doesn't work in any cases(don't know why) afterall, but func = getattr(self, 'title'); func();
does. So, maybe is better to use getattr()
instead– ioaniatr
Aug 16 '18 at 16:52
self.__getattribute__('title')
doesn't work in any cases(don't know why) afterall, but func = getattr(self, 'title'); func();
does. So, maybe is better to use getattr()
instead– ioaniatr
Aug 16 '18 at 16:52
5
5
Can people who don't know python please stop upvoting this junk? Use
getattr
instead.– Aran-Fey
Oct 23 '18 at 5:19
Can people who don't know python please stop upvoting this junk? Use
getattr
instead.– Aran-Fey
Oct 23 '18 at 5:19
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Mar 26 at 18:15
SerjikSerjik
5,26464360
5,26464360
add a comment |
add a comment |
protected by Bo Persson Jan 6 '13 at 23:06
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?