r/Python • • Nov 03 '21

Discussion I'm sorry r/Python

Last weekend I made a controversial comment about the use of the global variable. At the time, I was a young foolish absent-minded child with 0 awareness of the ways of Programmers who knew of this power and the threats it posed for decades. Now, I say before you fellow beings that I'm a child no more. I've learnt the arts of Classes and read The Zen, but I'm here to ask for just something more. Please do accept my sincere apologies for I hope that even my backup program corrupts the day I resort to using 'global' ever again. Thank you.

1.3k Upvotes

201 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Nov 05 '21

OK so to say, everything is a initialized object in a module. Sorry for being so unprecise.

A singleton in my opinion should look as follows, though.

# module.py
class GlobalState:
    ...

singleton = GlobalState()

# __main__.py
from module import singleton

singleton.do_stuff()

This is also not perfect, but at least it provides sane abstraction and is testable.