default variable in python $_

rh0dium steven.klass at gmail.com
Wed Oct 11 16:59:40 CEST 2006


Hi Maria,

This is exactly what I was looking for.  I (as others have asked me to)
cleared my head of the other languages, but was mearly giving perl as
an example indicating the compactness I was after.

Thanks Maria!!

MaR wrote:
> rh0dium wrote:
> > Hi all,
> >
> > So I have this simple little routine..  say like this..
> >
> >
> > def foo()
> >    return {"a":"b", "b":"c"}
> >
> > if foo():
> >    print "Have foo"
> >
> >
> > Now I want the dictionary item a (ie. b)
> >
> > How can I do it the above way or do I still have to go like this..
> >
> > def foo()
> >    return {"a":"b", "b":"c"}
> >
> > z = foo()
> > if z:
> >    print "Have foo"
> >    print z['a']
> >
> > This is where $_ in perl is awesome - There must be a default variable
> > in python right?
>
> As said in earlier response, such a default variable is *dangerous* at
> best!
> Not knowing much about Perl and guessing that the $_ is a global
> storage space, my immediate thought is; What happens if you have
> multiple threads?
>
> The example is too simplified to give any clues as to what you are
> needing the feature for.
> Guessing that you want to generate some dict() and use the result once
> and then discard, write:
>
> foo_default = 1
> def foo(): return(generate_some_dict())
>
> you can further write
>
> foo().get('a', foo_default)
>
> giving compact code and ensuring that you get a well defined result
> regardless what dictionary keys there are.




More information about the Python-list mailing list