[Tutor] Fixing Globals

Kwpolska kwpolska at gmail.com
Sat Mar 16 20:11:19 CET 2013


On Sat, Mar 16, 2013 at 8:04 PM,  <kendy at kendy.org> wrote:
> Dear Tutor
>
> Global constants and variables are bad. But what's better? I've heard some
> suggestions, but haven't seen much actual code showing how to improve globals. I
> don't like:
>
> * Passing a lot of individual arguments.
> * Creating a structure with unrelated elements.
> * Passing a structure, as an argument, through a function that uses only one (or
> none of the) elements in the structure.
>
> I created an example (below), that could be written with global constants and
> variables. How would you suggest handling something like this? (I don't need you
> to stick to my example.)
>
> #!/usr/bin/python
>
> START = '<'
> END = '>'
>
[snip]
> def stuff():
>     if c == START or c == END:
>         foo_the_bar =

Ugh, you don’t need variables for this.  You should do:

    if c == '<' or c == '>'

Or, even more Pythonically:

    if c in '<>'

Now, for other cases, I suggest OOP and class member values or stuff like that.


-- 
Kwpolska <http://kwpolska.tk> | GPG KEY: 5EAAEA16
stop html mail                | always bottom-post
http://asciiribbon.org        | http://caliburn.nl/topposting.html


More information about the Tutor mailing list