Function to avoid a global variable
Bob van der Poel
bob at mellowood.ca
Mon Apr 27 21:44:56 EDT 2020
Oh my, that is very cool! So, I can do this:
def foo(i):
if not 'bar' in foo.__dict__:
foo.bar = 5
foo.bar += i
for a in range(10):
foo(1)
print (foo.bar)
Thanks. I will have to play more with this.
On Mon, Apr 27, 2020 at 5:31 PM Michael Torrie <torriem at gmail.com> wrote:
> On 4/27/20 10:39 AM, Bob van der Poel wrote:
> > Thanks Chris!
> >
> > At least my code isn't (quite!) as bad as the xkcd example :)
> >
> > Guess my "concern" is using the initialized array in the function:
> >
> > def myfunct(a, b, c=array[0,1,2,3] )
> >
> > always feels like an abuse.
> >
> > Has anyone seriously considered implementing a true static variable in a
> > function? Is there a PEP?
>
> There's actually no need. You can create attributes on the function
> itself, just like a regular object:
>
> def foo():
> if not 'bar' in foo.__dict__:
> foo.bar = 5
>
> print (foo.bar)
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
--
**** Listen to my FREE CD at http://www.mellowood.ca/music/cedars ****
Bob van der Poel ** Wynndel, British Columbia, CANADA **
EMAIL: bob at mellowood.ca
WWW: http://www.mellowood.ca
More information about the Python-list
mailing list