0

I have 2 extremely simple python files. I am doing this as a test to see if blah2.py sees the updated version of the two variables initially declared as None after the 2 second sleep. The files are as below:

blah1.py

from time import sleep
import blah2

movingVariable1 = None
movingVariable2 = None

sleep(2)
movingVariable1 = "sup"
movingVariable2 = "blahhh"
blah2.myFunc()

blah2.py

from blah1 import movingVariable1
from blah1 import movingVariable2

def myFunc():
    global movingVariable1
    global movingVariable2
    print(movingVariable1)
    print(movingVariable2)

I am getting the following error though, and I'm not sure why.

 Traceback (most recent call last):
  File "blah1.py", line 2, in <module>
    import blah2
  File "/home/pi/blah2.py", line 1, in <module>
    from blah1 import movingVariable1
  File "/home/pi/blah1.py", line 10, in <module>
    blah2.myFunc()
AttributeError: module 'blah2' has no attribute 'myFunc'

myFunc() clearly is defined as a function though in blah2.py. Can anyone explain what I am doing wrong in this basic example?

1 Answer 1

1

You are creating a circular dependency in blah2.py

In your example blah1 imports blah2 which in turn imports blah1 which will again import blah2 and so on...

Make movingVariable & movingVariable2 parameters for myFunc and remove import of blah1.py in blah2.py.

Reply to follow-up

# blah1.py
from blah1 import movingVariable1
from blah1 import movingVariable2

def myFunc():
    global movingVariable1
    global movingVariable2
    print(movingVariable1)
    print(movingVariable2)
# blah2.py
from time import sleep

movingVariable1 = None
movingVariable2 = None

if __name__ =='__main__':
    import blah2
    sleep(2)
    movingVariable1 = "sup"
    movingVariable2 = "blahhh"
    blah2.myFunc()

If you change it like this it will work. Since when blah2 import blah1.py it does not see import blah2 since then __name__ will not be equal to __main__.

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

2 Comments

Does just importing those 2 variables, not the whole blah1.py, still cause the circular dependency? I knew it would if I imported the entire file, but thought it wouldn't with just individual variables.
Please accept the answer if your problem was solved.

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.