Function attributes again

Fredrik Aronsson d98aron at dtek.chalmers.se
Wed May 30 12:12:42 EDT 2001


In article <h71ahtoc3gn0eft2se5obpoh5kpndqqbua at 4ax.com>,
	Fernando Rodríguez <spamers at must.die> writes:
> Hi!
> 
> 	How can I check (from within a function) if it has attributes?  I
> tried if __dict__ == None in the definition, but it doesn't work:
> 
> def f(a, b):
> 	z = 0
> 	if __dict__ == None:
> 		__dict__['c'] = 4
> 	
> 	return z + a + b
> 
>>>> f(8,3)
> Traceback (most recent call last):
>   File "<pyshell#39>", line 1, in ?
>     f(8,3)
>   File "<pyshell#28>", line 3, in f
>     if __dict__ == None:
> NameError: global name '__dict__' is not defined
> 
> What's going on? O:-)

You're trying to access __dict__ as a global variable, but you probably
want to access your functions func_dict.

>>> def f():
...   print f.x
... 
>>> f.x=31426
>>> f.func_dict 
{'x': 31426}

/Fredrik

hint: dir is handy if you want to know what attributes 
and functions a class, object or function etc. have.

>>> dir(f)
['__dict__', '__doc__', '__name__', 'func_closure', 'func_code',
'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name',
'x']



More information about the Python-list mailing list