Can global variable be passed into Python function?

Marko Rauhamaa marko at pacujo.net
Sat Mar 1 11:31:39 CET 2014


Ben Finney <ben+python at benfinney.id.au>:

> Since you don't care about identity, only that the objects have
> different values, you should be comparing for equality with ‘==’.

Ok, one last attempt.

I need *identifiers*. I could simply define:

   class ABC:
       A = object()
       B = object()
       C = object()

The program would work perfectly.

Except, if it's got a bug. I know self.abc contains either A, B or C,
but which one? Printing out self.abc won't give me any help. I could
print out ABC.A, ABC.B and ABC.C and see which one matches, but that's
cumbersome.

The next variant is to use objects that have names:

   class Symbol:
       def __init__(self, name):
           self.name = name
       def __str__(self):
           return self.name

   class ABC:
       A = Symbol("A")
       B = Symbol("B")
       C = Symbol("C")


The same program still works (and still uses "is" for identity tests,
mind you).

The next realization is that the Symbol class is completely redundant as
any string object would fit the bill. Hence we can reduce the visual
clutter by simply defining:

   class ABC:
       A = "A"
       B = "B"
       C = "C"

The same program still works (and still uses "is" for identity tests,
mind you).


Marko


PS The only remaining redundancy is having to repeat the symbol name in
every assignment. If Python (like Lisp) had a builtin symbol datatype,
you wouldn't have to define anything at all but simply assign something
like this:

    self.abc = $A

where $A would be a symbol.



More information about the Python-list mailing list