3

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.

2
  • 2
    A.py does not do anything with the variables. It merely tries to access an entry in a dictionary. Did you mean to say myClass.dict["variable"] = "value" (or something to that effect)? Commented Jan 25, 2012 at 22:22
  • Wanted you all to know that the issue was slightly more insidious, and thank you for your help. It was importing the same files through two paths: one imported project.classes.myClass while the other imported just classes.myClass, creating two separate instances. The post that this was reduced from is this one: Shared/Global Dictionary in Django Between URLs and Context Processor Commented Jan 25, 2012 at 22:45

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

... because modules that were imported before (being in the same process, o.c.) are saved in the sys.modules dictionary. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.