Anonymus functions revisited
Ron
radam2 at tampabay.rr.com
Tue Mar 22 21:11:40 EST 2005
On Tue, 22 Mar 2005 18:15:25 -0500, "George Sakkis"
<gsakkis at rutgers.edu> wrote:
>"Ron" <radam2 at tampabay.rr.com> wrote:
>> On Tue, 22 Mar 2005 21:56:57 GMT, Ron <radam2 at tampabay.rr.com> wrote:
>>
>> >Why should a function not create a local varable of an argument if the
>> >varable doesn't exist and a default value is given?
>>
>
>Yeap.. a simple one-liner can do the trick:
>
>def makeVars(**nameVals):
> sys._getframe(1).f_locals.update(nameVals)
>
>try: b
>except NameError: print "Before makeVars: NameError"
>else: print "Before makeVars: Not NameError"
>makeVars(b=2)
>try: b
>except NameError: print "After makeVars: NameError"
>else: print "After makeVars: Not NameError"
>
>George
>
Cool! Thanks George, so I can do this:
# Set a varable to a default value if it doesn't exist.
# Return the same value back if it does.
# Use: varable = dfvalue( varable=object)
def defvalue(**var):
if var.keys()[0] not in sys._getframe(1).f_locals.keys():
return var.values()[0]
return sys._getframe(1).f_locals[var.keys()[0]]
f = defvalue(f=0)
print f # 0
g = 19
g = defvalue(g=0)
print g # 19
Would there be any problems with using this function?
Not sure where I need it. Was thinking it could be used inside
expressions somehow, and it was an iteresting problem. ;)
Ron
More information about the Python-list
mailing list