encapsulating a global variable

Dieter Maurer dieter at handshake.de
Tue Feb 25 12:17:00 EST 2020


BlindAnagram wrote at 2020-2-25 12:38 +0000:
>I would appreciate advice on whether it is possible to avoid the use of
>a global variable used in a function by encapsulating it in a class
>without maaking any changes to the call interface (which I cannot change).
>
>I have:
>
>----------------
>seen = dict()
>
>def get_it(piece):
>   ...
>   return seen[piece]
>----------------
>
>and I am wondering if it is possible to use a class something like
>
>----------------
>class get_it(object):
>
>  seen = dict()
>
>  def __call__(piece):
>    return seen[piece]
>----------------
>
>to avoid the global variable.

Apparently, you are ready to change the function.
In this case, you might be interested in `rebindFunction` from
the package `dm.reuse`.
Its primary purpose is to reuse a foreign function in one's own
code with minor modifications. One of the supported minor
modifications is to change globals seen by the function.


More information about the Python-list mailing list