I've a main file (main.py):
execfile("library.py")
#import library : DOESN'T WORK
class c_config(object):
static_var=3
print(c_config.static_var) # Works both ways
obj=another()
print(obj.dynamic) # Works with execfile and doesn't work with import
and a file of my library with my funcs and classes and so on (library.py):
class another(object):
def __init__(self):
self.dynamic=c_config.static_var+1.3
I would like to import my library file with
import library
which causes my imported object "another()" to not see the config class "c_config" with static_var, even though I imported it into this file with the config class...
The execfile does it (not sure why). I'd like to construct it so that I use import.
Why can the object "obj=another()" not access the class "c_config" in the file it's been imported into?
The most likely problem is that you are saying
from test_bib.py import *
when you should be using:
from test_bib import *
Imports don't need the .py
extension - in fact it raises an ImportError
.
This also goes for library.py
. As you can run it with execfile
it seems that the library.py
file is in the same directory as your main.py
. In which case you should also be able to do the following:
import library
In that case your another
class can be accessed by:
obj = library.another()
EDIT:
So looking at your latest edit it looks like c_config
is meant to be used in library.py
, whereas it is defined in main.py
.
This wouldn't work with import library
in main
as you need to have imported c_config
into library.py
. But importing main
would create a circular import. It's generally best to keep interdependent classes in the same file.
Not sure why execfile
is working, unless it is silently failing. But I'm not at my computer right now so will research once I am.