encapsulating a global variable

Chris Angelico rosuav at gmail.com
Tue Feb 25 09:13:57 EST 2020


On Wed, Feb 26, 2020 at 12:11 AM BlindAnagram <blindanagram at nowhere.com> wrote:
>
> On 25/02/2020 12:56, Chris Angelico wrote:
> > On Tue, Feb 25, 2020 at 11:41 PM BlindAnagram <blindanagram at nowhere.com> wrote:
> >>
> >> 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).
> >
> > Why bother? If you aren't changing where the function's called, then
> > its state is effectively global anyway, so what's the point of the
> > class?
>
> It's a good question!
>
> The main reason is that I would like to know if it is possible as I then
> have a choice.  The choice might not be there.
>

Well, yes, you can, but you would need a global instance of that class
(or use the global class object itself). So you'd still have a global.

But if this is a transitional thing, then the answer is a resounding
YES. You can start by packaging up all your state with a class, and
have a single global instance of that class; but then you can rework
your function to take an optional parameter which is a non-global
instance of the class. Then all your state is kept in there, and you
actually truly *do* avoid global state. As a good example of how this
works, check out Python's random module - you can call
random.randrange() to get a random number in a particular range, or
you can instantiate your own random.Random() object and call its
randrange() method. The first form uses global state; the second form
doesn't.

ChrisA


More information about the Python-list mailing list