Anonymus functions revisited

Duncan Booth duncan.booth at invalid.invalid
Fri Mar 25 11:09:50 CET 2005

Ron wrote:
> It's interesting that there is a whole is_"type"_() group of functions
> in the inspect module, but not a is_defined().  Maybe I just haven't
> found it yet.

I've never found any need for an is_defined function. If in doubt I just 
make sure and initialise all variables to a suitable value before use. 
However, I'll assume you have a good use case.

> #############
> def if_not_defined(v, dv=None, lv=locals()):
>     if lv.has_key(v):
>         return lv[v]
>     return dv

I don't see the point of the default argument. locals() at the global level 
simply returns globals, so you might as well use that. A more useful 
default would be the caller's locals.

> def is_defined(v, lv=locals()):
>     if lv.has_key(v):
>         return True
>     False

Same comments, plus the whole 'if on a boolean to return a boolean' is a 
bit redundant.

Try something on these lines:

>>> import inspect
>>> def is_defined(name, lv=None):
	if lv is None:
		lv = inspect.currentframe().f_back.f_locals
	return name in lv

>>> is_defined('abc')
>>> abc = 3
>>> is_defined('abc')
>>> def f(x):
	print is_defined('x')
	print is_defined('y')
	y = 0
	print is_defined('y')

>>> f(2)

> # Shorten names and pass locals() with lambas for 
> # convenience.   (This needs to be in the function 
> # where they are used or it will break.  
> # Another use for lamba!   ;)
> ifnd = lambda v, dv, lv=locals(): if_not_defined(v,dv,lv)
> isa = lambda v, lv=locals(): is_defined(v, lv)

There is no need for lambda here, it adds nothing. Use a 'def'.

More information about the Python-list mailing list