top | item 37246236

(no title)

Yajirobe | 2 years ago

So it’s supposed to be ‘exemplary’ and ‘beautiful’ but literally the first script I opened had global variables used. That’s not my idea of elegant Python.

discuss

order

Etherlord87|2 years ago

In Python every module is an object. It therefore makes less sense (in less situations it makes sense) to use classes, and a 'global' is a variable global to the module. It's like having a class, and calling attributes of the class 'globals', because they can be accessed by all methods of the class.

This and the fact Python is often used in the context of writing simple utilities, where globals (even without the defense above) are perfectly fine (because it's not a huge codebase with namespace collisions etc.).

Using absolute axioms like "globals are always bad" and religiously applying them is a toxic attitude in my opinion.

cjalmeida|2 years ago

Exactly. Only "builtins" in Python polute the global scope. Module globals are closer to singleton instance variables.

quietbritishjim|2 years ago

Elegant means written in the simplest, clearest way possible.

Agreed, a complex application riddled with global variables is not elegant.

In a fifty line self-contained script, global variables are often the simplest way to go. Turning the code into a reusable class with member variables, which will never be reused, is not simpler. YAGNI.