Can you use -getattr- to get a function in the current module?

S

Sergio Correia

This works:

# Module spam.py

import eggs

print getattr(eggs, 'omelet')(100)

That is, I just call the function omelet inside the module eggs and
evaulate it with the argument 100.

But what if the function 'omelet' is in the module where I do the
getattr (that is, in spam.py). If I do any of this

print getattr(spam, 'omelet')(100)
print getattr('','omelet')(100)
print getattr('omelet')(100)

It wont work. Any ideas?

Thanks,
Sergio
 
A

Alex Martelli

Sergio Correia said:
This works:

# Module spam.py

import eggs

print getattr(eggs, 'omelet')(100)

That is, I just call the function omelet inside the module eggs and
evaulate it with the argument 100.

But what if the function 'omelet' is in the module where I do the
getattr (that is, in spam.py). If I do any of this

print getattr(spam, 'omelet')(100)
print getattr('','omelet')(100)
print getattr('omelet')(100)

It wont work. Any ideas?

globals() returns a dict of all globals defined so far, so, _after_ 'def
omelet ...' has executed, globals()['omelet'](100) should be OK.


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top