Although the variable should be imported, I get "name X is not defined" exception.
main.py
from config import *
from utils import *
say_hello()
utils.py
from config import *
def say_hello():
print(config_var)
config.py
from utils import *
config_var = "Hello"
Trying to run "main.py":
Traceback (most recent call last):
File "main.py", line 3, in
say_hello()
File "C:\Users\utils.py", line 3, in say_hello
print(config_var)
NameError: name 'config_var' is not defined
What happened here? Why some_var is not accessible from utils.py?
You are importing config in util and util in config which will causing this error(create cross loop). remove from utils import * from config.py and then try this.
And in main.py you don't need to import the from config import * unless you are using variables from config directly in your main()
you should also import config.config_var, since this variable belongs to that specific module
You are creating to many import statements perhaps try the following below, but also you need to define a parameter in utils.py if you are passing a parameter through there.
In utils.py we require a parameter to be passed since you want to print out the appropriate value, In config.py you are defining a value. Then in main.py as discussed before using the wildcard operator "*" isn't entirely good in this situation then in order to call the respective functions you need to address them through their file name
In utils.py :
def say_hello(config_var):
print(config_var)
In config.py
config_var = "Hello"
Then in main.py
import config as cn
import utils as ut
ut.say_hello(cn.config_var)
Check out this thread for how to write python modules as well How to write a Python module/package?
Related
First of all here is my directory structure:
Root
- models
car.py
__init__.py
hello.py
Inside __init__.py I have the following:
__all__ = ["car"]
Inside hello.py I try to import everything from models folder:
from models import *
car = Car()
This gives me the error:
Traceback (most recent call last):
File "hello.py", line 4, in <module>
car = Car()
NameError: name 'Car' is not defined
What am I doing wrong?
You will have to specify what class you would like to import into the attribute __all__ of your __init__.py file. See below the example:
from car import *
__all__ = ["Car"]
If you want to have the class Car directly accessible in hello.py after you do from models import *, in the __init__.py file, put from models.car import Car.
__all__, on the other hand, typically lists names of modules, like what you have above. You could change hello.py to be as follows and your current __init__.py that consists of __all__ = ["car"] will work:
from models import *
car_obj = car.Car() # Reference module.class instead of just the class
From the python docs:
if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered.
This means that your hello.py has just imported the car module into it's namespace, not the Car class. Therefore this would work.
from models import *
auto = car.Car()
You missed one step there.
Try:
from models import *
car = car.Car()
Or try:
from models.car import *
car = Car()
__all__ just controls what will be exported by using * in current scope.
In your case, Car is not in your __init__.py's scope. So it is meaningless.
To solve this problem, you need to import Car into __init__.py's scope, that's all.
I understand that you think just by using __all__, you can directly access the class in car.py, but that's not true. __all__ does nothing else but control exports in current scope.
i want to make a sample package in python 2.7 just to clear my concepts whose structure looks like this:
calculator/
main.py
operations/
file1.py
file2.py
__init__.py
new_operations/
__init__.py
file3.py
main.py content: (this file is present inside calculator folder)
from operations import power
print power(2,2)
__init__.py content: (this file is present inside operations folder)
from .file1 import add
from .file1 import sub
from .file2 import mul
from .file2 import div
file1.py content: (this file is present inside operations folder)
def add(a,b):
return(a+b)
def sub(a,b):
return(a-b)
file2.py content: (this file is present inside operations folder)
def mul(a,b):
return(a*b)
def div(a,b):
return(a/b)
__init__.py content: (this file is present inside new_operations folder)
from .file3 import power
file3.py content: (this file is present inside new_operations folder)
def power(a,b):
return(a**b)
Now, when i run main.py, i got following error:
Traceback (most recent call last):
File "C:\Python27\mycodes\calculator\main.py", line 3, in <module>
from operations import power
ImportError: cannot import name power
Can anyone tell me, what mistake i am doing ? Help me.
Use the following line in your "main.py" file:
from operations.new_operations import power
You are missing an 'add' function in your calculator module. If you create an 'add' function, I would assume that the code would work.
maybe try doing this in the module calculator:
def add(num1,num2):
print(num1+num2)
return num1+num2;
If you don't want it to print while calculating, remove the print statement.
Hope this helps!
I've been trying to import some python classes which are defined in a child directory. The directory structure is as follows:
workspace/
__init__.py
main.py
checker/
__init__.py
baseChecker.py
gChecker.py
The baseChecker.py looks similar to:
import urllib
class BaseChecker(object):
# SOME METHODS HERE
The gChecker.py file:
import baseChecker # should import baseChecker.py
class GChecker(BaseChecker): # gives a TypeError: Error when calling the metaclass bases
# SOME METHODS WHICH USE URLLIB
And finally the main.py file:
import ?????
gChecker = GChecker()
gChecker.someStuff() # which uses urllib
My intention is to be able to run main.py file and call instantiate the classes under the checker/ directory. But I would like to avoid importing urllib from each file (if it is possible).
Note that both the __init__.py are empty files.
I have already tried calling from checker.gChecker import GChecker in main.py but a ImportError: No module named checker.gChecker shows.
In the posted code, in gChecker.py, you need to do
from baseChecker import BaseChecker
instead of import baseChecker
Otherwise you get
NameError: name 'BaseChecker' is not defined
Also with the mentioned folders structure you don't need checker module to be in the PYTHONPATH in order to be visible by main.py
Then in main.y you can do:
from checker import gChecker.GChecker
I've got a class that I'm trying to write called dbObject and I'm trying to import it from a script in a different folder. My structure is as follows:
/var/www/html/py/testobj.py
/var/www/html/py/obj/dbObject.py
/var/www/html/py/obj/__init__.py
Now, __init__.py is an empty file. Here are the contents of dbObject.py:
class dbObject:
def __init__():
print "Constructor?"
def test():
print "Testing"
And here's the contents of testobj.py:
#!/usr/bin/python
import sys
sys.path.append("/var/www/html/py")
import obj.dbObject
db = dbObject()
When I run this, I get:
Traceback (most recent call last):
File "testobj.py", line 7, in <module>
db = dbObject()
NameError: name 'dbObject' is not defined
I'm new to Python, so I'm very confused as to what I'm doing wrong. Could someone please point me in the right direction?
EDIT: Thanks to Martijn Pieters' answer I modified my testobj.py as follows:
#!/usr/bin/python
import sys
sys.path.append("/var/www/html/py")
sys.path.append("/var/www/html/py/dev")
from obj.dbObject import dbObject
db = dbObject()
However, now when I run it I get this error:
Traceback (most recent call last):
File "testobj.py", line 7, in <module>
db = dbObject()
TypeError: __init__() takes no arguments (1 given)
Is this referring to my init.py or the constructor within dbObject?
EDIT(2): Solved that one myself, the constructor must be able to take at least one parameter - a reference to itself. Simple fix. Looks like this problem is solved!
EDIT (Final): This is nice - I can cut out the import sys and sys.path.append lines and it still works in this instance. Lovely.
You need to import the class from the module:
from obj.dbObject import dbObject
This adds the class dbObject directly to your local namespace.
Your statement import obj.dbObject adds the name obj to the local namespace, so you could also do this instead:
db = obj.dbObject.dbObject()
because obj.dbObject is the dbObject.py module in your obj package directory.
my dir location,i am in a.py:
my_Project
|----blog
|-----__init__.py
|-----a.py
|-----blog.py
when i 'from blog import something' in a.py , it show error:
from blog import BaseRequestHandler
ImportError: cannot import name BaseRequestHandler
i think it import the blog folder,not the blog.py
so how to import the blog.py
updated
when i use 'blog.blog', it show this:
from blog.blog import BaseRequestHandler
ImportError: No module named blog
updated2
my sys.path is :
['D:\\zjm_code', 'D:\\Python25\\lib\\site-packages\\setuptools-0.6c11-py2.5.egg', 'D:\\Python25\\lib\\site-packages\\whoosh-0.3.18-py2.5.egg', 'C:\\WINDOWS\\system32\\python25.zip', 'D:\\Python25\\DLLs', 'D:\\Python25\\lib', 'D:\\Python25\\lib\\plat-win', 'D:\\Python25\\lib\\lib-tk', 'D:\\Python25', 'D:\\Python25\\lib\\site-packages', 'D:\\Python25\\lib\\site-packages\\PIL']
zjm_code
|-----a.py
|-----b.py
a.py is :
c="ccc"
b.py is :
from a import c
print c
and when i execute b.py ,i show this:
> "D:\Python25\pythonw.exe" "D:\zjm_code\b.py"
Traceback (most recent call last):
File "D:\zjm_code\b.py", line 2, in <module>
from a import c
ImportError: cannot import name c
When you are in a.py, import blog should import the local blog.py and nothing else. Quoting the docs:
modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script
So my guess is that somehow, the name BaseRequestHandler is not defined in the file blog.py.
what happens when you:
import blog
Try outputting your sys.path, in order to make sure that you have the right dir to call the module from.