Testing if a global is defined in a module

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jul 5 01:13:25 CEST 2011

Tim Johnson wrote:

>   dir(<targetmodule>) will also show globals from other modules imported
>   by the target module. So I would need a way to distinguish between
>   those imported and those defined in <targetmodule>

Why would you want to do that? Importing *is* a definition in

Consider these two code snippets:

from math import pi

import math
tau = 2*math.pi
del math

Why do you think it is necessary to distinguish pi from tau? Both names are
local to the current namespace.

>   print(dir(targetmodule)) =>
>    ['Install', 'TestAddresses', '__builtins__', '__doc__',
>    '__file__', '__name__', '__package__', 'chmod', 'consoleMessage',
>    'cp', 'debug', 'erh', 'exists', 'halt', 'is_list', 'load',
>    'makePath', 'mkdir', 'process', 'sys', 'traceback', 'usingCgi']
>    where 'TestAddresses' is a member of an imported module and

You are mistaken. TestAddresses is *not* a member of an imported module. It
is a member of the current module, which may or may not happen to point to
the same object as the other module as well.

>    'usingCgi' is the only data variable defined in <targetmodule>

It seems to me that your approach here is unnecessarily complex and fragile.
I don't know what problem you are trying to solve, but trying to solve it
by intraspecting differences that aren't differences is surely the wrong
way to do it.


More information about the Python-list mailing list