Function to avoid a global variable
ast
ast at invalid
Tue Apr 28 03:52:37 EDT 2020
Le 28/04/2020 à 09:39, Antoon Pardon a écrit :
>
>
> Op 27/04/20 om 18:39 schreef Bob van der Poel:
>> 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?
>
> You can emulate a static variable is with a closure.
>
> def make_parseStack():
>
> depth = 0
>
> def parseStack(inc):
> nonlocal depth
>
> if depth > 50:
> ... report error and die nicely
> depth += inc
>
> return parseStack
>
> parseStack = make_parseStack()
>
funny !
So we found 4 different ways to handle a memory in a function
1- Use a function parameter with a mutable default value
2- Use a function attribute
3- Use a callable object, and store your stuff inside an object attr
4- Use a closure to emulate a static function variable
Any more ?
More information about the Python-list
mailing list