On 25/02/2020 14:13, Chris Angelico wrote: > On Wed, Feb 26, 2020 at 12:11 AM BlindAnagram <blindanag...@nowhere.com> > wrote: >> >> On 25/02/2020 12:56, Chris Angelico wrote: >>> On Tue, Feb 25, 2020 at 11:41 PM BlindAnagram <blindanag...@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.
Thanks, I think I understand most of this but the eample will help a lot. My interest in this stems from wanting to keep the dictionary only available to the function that uses it and also a worry about being called from threaded code. Brian -- https://mail.python.org/mailman/listinfo/python-list