Anonymus functions revisited
Ron
radam2 at tampabay.rr.com
Thu Mar 24 12:38:46 EST 2005
On 24 Mar 2005 09:20:52 GMT, Duncan Booth
<duncan.booth at invalid.invalid> wrote:
>Ron wrote:
>
>>>> A working makeVars seems not to be different from
>>>>
>>>> def makeVars(**nameVals):
>>>> globals().update(nameVals)
>>>
>>>Not quite. If Ron can come up with a working makeVars it would update
>>>the caller's globals whereas what you just posted updates makeVar's
>>>globals so there is a difference (when the makeVars and the calling
>>>function are in different modules), just not a very useful one.
>>
>> How about this one? The only reliable way I found to do it is to
>> pass locals() to the function.
>
>Yes, but you are still missing the fundamental point. The locals()
>dictionary is not guaranteed to do anything useful if you update it. The
>current C implementation will reflect changes in the locals dictionary if
>you call locals() from global scope or in a few other circumstances, but
>this is simply an implementation detail.
Nope, Didn't miss the point. The functions return a value, not create
it from within.
>If you want to update global variables then use globals() or setattr on the
>module. Only use locals() to access local variables indirectly, never to
>try and set them.
Good advise. :)
One of pythons weak points is it is sometimes difficult to 'monitor
and confirm' what is happening leading to confusing try/except
constructions.
Having the function is_defined() and if_not_defined() have the
advantage that they can be use in expressions where try/except can't.
And the source code could be more compact and more readable.
The disadvantage is the functions are quite a bit slower than
try/except, probably due to the function call over head.
If they were built in, they may be as fast as the try/except and there
wouldn't be issues with having to passing locals() or globals() name
dictionaries.
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.
#############
def if_not_defined(v, dv=None, lv=locals()):
if lv.has_key(v):
return lv[v]
return dv
def is_defined(v, lv=locals()):
if lv.has_key(v):
return True
False
# 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)
# Totally useless routine. ;)
import random
for n in range(10):
# Delete a random x,y,z coordinate to
# simulate an unreliable data source.
d = random.choice([1,2,3])
if d==1:
if isa('x'): del x
elif d==2:
if isa('y'): del y
else:
if isa('z'): del z
# Replace the missing variable with a random number.
r = int(random.random()*100)
x, y, z = ifnd('x',r), ifnd('y',r), ifnd('z',r)
print x, y, z
###########
More information about the Python-list
mailing list