Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Global Variable Through Import?

Is this form of global variable declaration good practice in Python? My dictionary has no data in B.py in some cases. Just seems inconsistent.

classes.py

class Aclass:
    dict = {}

myClass = Aclass()

A.py:

from classes import myClass

myClass.dict["variable"]

B.py:

from classes import myClass

print str(myClass.dict)

A.py is processed before B.py. This prints an empty dict {} for me.

This is a simplified question from previous post: Shared/Global Dictionary in Django Between URLs and Context Processor. Your insight is appreciated.

like image 778
garromark Avatar asked Sep 24 '26 19:09

garromark


1 Answers

if in A.py you change it to

myClass.dict["variable"]="hello"

(as pointed out in comments)

then the question becomes interesting.

it's ok but it's better to have another interface (functions, methods) to that data. It's a way to store a state of the module. The object you called myClass (!) is the same both from a and b.

multiple imports are safe and do nothing except to return the same loaded module.

like image 178
Johan Lundberg Avatar answered Sep 26 '26 11:09

Johan Lundberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!