mardi 18 avril 2017

Can't understand why importing global variables works for running a program and fails for tests

A little embarrassed asking this because I've been writing python for a while, but apparently I still seem to not fully understand imports. My directory looks as follows (python 3.5, using conda structure):

  • app_name/
    • app_name/
      • foo.py
      • sub_dir/
        • bar.py
    • tests/
      • test_bar.py

in foo.py, I have something that looks as follows:

class MyClass:
    def __init__(self, test):
        self.test = test
        global my_global
        my_global = self.test

and in bar.py, I am able to do: import app_name.foo as foo_bar, then in my code I can run foo_bar.my_global with no problem.

What I don't understand is why in my test_bar.py, when I test the file 'bar.py' and run the test the global import gives an attribute error. What am I missing??

In general, I don't like globals and will eventually fix this implementation. But I figured an explanation of why this is happening would still be helpful. Please let me know if you need more details on the code structure. Thanks!

Aucun commentaire:

Enregistrer un commentaire