Use global, or not

Cecil Westerhof Cecil at decebal.nl
Sat Jun 29 07:42:45 EDT 2019


DL Neil <PythonList at DancesWithMice.info> writes:

> On 29/06/19 1:44 AM, Cecil Westerhof wrote:
>> I have written a GUI program where I have quit a few global variables.
>> I did not like this, so I now use one global dict. Something like:
>>      global global_dict
> ...
>
>> Is that an acceptable way to do this?
>
>
> If it works, isn't that the largest part of "acceptable"?

Depends on your way of thinking. ;-)
I think it is always best when you write in a language to do it in
that languages way. In this case Python.
I also think this is a program that could be interesting to share.
Then it becomes even more important to do it the Python way.
And my experience is that when asking this type of question you often
get a tip that helps you make your program better.


> In each case, (previously discussed and/or below) you are taking
> advantage of "namespaces" to keep one 'lot' of values separated and
> distinct from others - as well as finding a means of 'passing them
> around'. The other half of the considerations is how the values are
> being retrieved/utilised within the mainline code.
>
> An alternative might be to use a class. Then accessing a single value
> becomes instance.attribute, but when you have need for several
> attribute's values or to compute a value from several attributes, an
> instance.method() may simplify things.

That was the other possibility I was thinking about. And that would be
maybe better. Because I now do things like:
    global_dict['messages']['created'].format(len(filepathArr))

much better would be:
    instance.created(len(filepathArr))

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof



More information about the Python-list mailing list