On 25/02/2020 14:14, Rhodri James wrote: > On 25/02/2020 12:38, BlindAnagram 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). >> >> 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. > > I wouldn't. Calling the class name creates an instance of the class, so > won't actually do what you want. You could rewrite the class and create > an instance to call instead: > > class GetIt: > seen = dict() > > def __call__(self, piece): > return GetIt.seen[piece] > > get_it = GetIt() > > but then you have a global class instance hanging around, which is not > actually any better than a global dictionary.
Thanks. Does that not have the advantage of preventing the global directory being directly fiddled with elsewhere? Which is one of my reasons for thinking about this. Brian -- https://mail.python.org/mailman/listinfo/python-list