Testing if a global is defined in a module

rantingrick rantingrick at gmail.com
Mon Jul 4 21:40:18 CEST 2011


On Jul 4, 1:11 pm, Tim Johnson <t... at johnsons-web.com> wrote:
> Using Python 2.6 on ubuntu 10.04.
> inspect module :
> I want to 'inspect' a module and get a list of all
> functions, classes and global variables in that module.
>
> ## A module has been imported, and we call `getmembers'
> members = inspect.getmembers(mod)
>
> ## While iterating thru `members', we test to see
> ## if an object is defined in the module.
> for m in members:
>   obj = m[1]
>   res = inspect.getmodule(obj)
> ## It appears that getmodule returns None for
> ## all but functions and classes.
>
> Example, for a module name `mvcInstall', when a class
> name `Install' that is defined in the module
> is passed as an argument to inspect.getmodule, the
> values returned is something like
> "<module 'mvcInstall' from
> '/home/tim/prj/cgi/libraries/python/mvcInstall.py'>"
> Likewise for functions defined in the module.
>
> ** But ** when global variables such as strings, booleans,
> integers are passed as an argument to getmodule, the
> value returned is `None'.
>
> What else can I do here?
> thanks
> --
> Tim
> tim at johnsons-web dot com or akwebsoft dot comhttp://www.akwebsoft.com

Well if you follow the python style guide (and most accepted styles
for global notation) then it's a trial exercise. You don't even have
to import anything!!! :)

>>> GLOBAL_STR = 'str'
>>> GLOBAL_FLOAT = 1.33333
>>> GLoBaL_Bs = ''
>>> dir()
['GLOBAL_FLOAT', 'GLOBAL_STR', 'GLoBaL_Bs', '__builtins__', '__doc__',
'__name__', '__package__', 'item']
>>> for item in dir():
	if item.isupper():
		print 'Found Global!', item


Found Global! GLOBAL_FLOAT
Found Global! GLOBAL_STR

;-)




More information about the Python-list mailing list