Function to avoid a global variable

Christian Gollwitzer auriocus at gmx.de
Tue Apr 28 04:01:37 EDT 2020


Am 28.04.20 um 09:54 schrieb ast:
>> 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 ?
>>
>>
> 
> 5- Use a global variable, of course

That's definitely the least recommendable solution. Global variable 
names pollute the global namespace, therefore they don't make sense to 
just store state within one function. They should be reserved to the 
case where multiple functions access a common state. Usually it is best 
to restrict the scope of a variable to the region of code where it 
necessarily needs to be available.

	Christian




More information about the Python-list mailing list