encapsulating a global variable

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Feb 25 17:49:16 EST 2020


On 26/02/20 3:56 am, BlindAnagram wrote:
> Does that not have the advantage of preventing the global
> directory being directly fiddled with elsewhere?

That depends on what you mean by "prevent". There is nothing
to stop any code from directly accessing the .seen attribute
of the class.

It might make it less likely that someone will inadvertently
write code that does this.

If there will only ever be one instance of the dict, another
approach would be to put it into a dedicated module together
with the functions that access it. That will give you the
same amount of protection, while ensuring that there really
is only one instance, and making this fact clear to anyone
reading the code.

-- 
Greg


More information about the Python-list mailing list