How to pass a reference to the current module
Steven D'Aprano
steve at REMOVE.THIS.cybersource.com.au
Sat Aug 4 00:37:39 EDT 2007
On Fri, 03 Aug 2007 18:45:21 -0700, Paul Rubin wrote:
> Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> writes:
>> namespace = module.__dict__
>> return namespace[name]
>
> Am I missing something? It's likely that I just don't understand
> the problem, but I don't understand these dictionary extractions
> for what I thought would be an attribute lookup:
Well, the *real* reason I used a __dict__ extraction was because I didn't
think of using getattr at the time, but as a post facto justification,
I'll point at the difficulty in using getattr for extracting a function
from the current module:
>>> def f(x):
... return x + 1
...
>>> func = getattr(???, 'f') # what should go there?
Maybe I've just got a blind spot, but I can't think of a way to use
getattr to get something from the current module. That would lead to
something like this:
def get_function_from_name(name, module=None):
if module is None:
return globals()[name] # or use locals()
else:
return getattr(name, module)
which is fine, I suppose, and I would have used it earlier if I had
thought of it *wink*
--
Steven.
More information about the Python-list
mailing list