Quantcast
Channel: Calling a function of a module by using its name (a string) - Stack Overflow
Viewing all articles
Browse latest Browse all 22

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

$
0
0

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 randombar = '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 somethingbar = '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 errorstry:    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 NameErrorexcept AttributeError:    # do domething or just...    print('Function does not exist')except NameError:    # do domething or just...    print('Module does not exist')

Viewing all articles
Browse latest Browse all 22

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>