I'm new to python and now learning how to to import a module or a function, but I got these posted errors. The python code is saved under the name: hello_module.py
python code:
def hello_func():
print ("Hello, World!")
hello_func()
import hello_module
hello_module.hello_func()
error message:
Traceback (most recent call last):
File "C:/Python33/hello_module.py", line 9, in <module>
import hello_module
File "C:/Python33\hello_module.py", line 10, in <module>
hello_module.hello_func()
AttributeError: 'module' object has no attribute 'hello_func'
You cannot and should not import your own module. You defined hello_func in the current namespace, just use that directly.
You can put the function in a separate file, then import that:
File foo.py:
def def hello_func():
print ("Hello, World!")
File bar.py:
import foo
foo.hello_func()
and run bar.py as a script.
If you try to import your own module, it'll import itself again, and when you do that you import an incomplete module. It won't have it's attributes set yet, so hello_module.hello_func doesn't yet exist, and that breaks.
Related
This question has been asked before. Even though I couldn't get an answer that solves this issue.
I have the following directory and subdirectories:
I have a function hello() in test1.py that I want to import in test2.py.
test1.py:
def hello():
print("hello")
test2.py:
import demoA.test1 as test1
test1.hello()
Output:
Traceback (most recent call last):
File "c:/Users/hasli/Documents/Projects/test/demoB/test2.py", line 1, in <module>
import demoA.test1 as test1
ModuleNotFoundError: No module named 'demoA'
This is exactly as explained in https://www.freecodecamp.org/news/module-not-found-error-in-python-solved/ but I can't access hello()
I am using python 3: Python 3.8.9
You need to add demoA to the list of paths used for import.
import sys
sys.path.append('..')
import demoA.test1 as test1
test1.hello()
I have been learning working with classes in python after learning OOPs in c++.
I am working on a project, where I have a class defined in one file, and an important function to be used in the class in the seperate file.
I have to call the class in the first file, but I am getting the ImportError.
Great, if you could help.
try1.py
from try2 import prnt
class a:
def __init__(self):
print("started")
def func1(self):
print("func1")
prnt()
try2.py
from try1 import a
b = a()
b.func1()
def prnt():
b.func()
As for eg, in the above example, when I am running try1.py, I am getting an ImportError: cannot import name 'prnt'.
You absolutely need to redesign your project. Even if you did manage to get away with the cyclic imports (ie by moving the import to inside the function - but don't do it) you will still get a NameError: name 'b' is not defined since b is not define in prnt.
Unless prnt can't be defined in class a (why?), consider defining prnt in a third, "utils" file and import it in both try1.py and try2.py and pass an object to it so it can access all of its attributes.
Just run your code, read the error, and deduct something from it.
When you run it, here is the error message :
Traceback (most recent call last):
File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in <module>
from temp2 import prnt
File "C:\Users\Kilian\Desktop\Code\Garbage\temp2.py", line 1, in <module>
from tmp import a
File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in <module>
from temp2 import prnt
ImportError: cannot import name prnt
Your script is trying to import something it already has tried to import earlier on. Python is probably deducing that it can't import it. :)
I have a project that tries to create a new module dynamically and then in a subsequent exec statement tries to import that module.
import imp
s="""
class MyClass(object):
def __init__(self):
pass
def foo(self):
pass
"""
mod = imp.new_module("testmodule.testA")
exec s in mod.__dict__
exec "import testmodule.testA"
But this throws this exception:
Traceback (most recent call last):
File "test.py", line 14, in <module>
exec "import testmodule.testA"
File "<string>", line 1, in <module>
ImportError: No module named testmodule.testA
I've tried several things: adding it to sys.modules, creating a scope dict containing the name and the module as well. But no dice. I can see testmodule.testA when I do a print locals() in my exec statement, but I can't import it. What am I missing here?
Thank you.
You'll need to add your module to the sys.modules structure for import to find it:
import sys
sys.modules['testmodule.testA'] = mod
You already have the module object however and there is not much point in importing it again. mod is a reference to what Python would otherwise 'import' already.
The following would work without an import call:
mod.MyClass
If you need the module in an exec call, add it to the namespace there:
exec 'instance = MyClass()' in {'MyClass': mod.MyClass}
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.
I'm trying to learn Python's SAX module from O'Reilly's Python and XML. I'm trying to run the following sample code, but I keep getting an error and I can't figure out why.
The first file is handlers.py:
class ArticleHandler(ContentHandler):
"""
A handler to deal with articles in XML
"""
def startElement(self, name, attrs):
print "Start element:", name
The second file is art.py, which imports the first file:
#!/usr/bin/env python
# art.py
import sys
from xml.sax import make_parser
from handlers import ArticleHandler
ch = ArticleHandler( )
saxparser = make_parser( )
saxparser.setContentHandler(ch)
saxparser.parse(sys.stdin)
When I try to run art.py, I get the following:
% python art.py < article.xml
Traceback (most recent call last):
File "art.py", line 7, in <module>
from handlers import ArticleHandler
File "~/handlers.py", line 1, in <module>
class ArticleHandler(ContentHandler):
NameError: name 'ContentHandler' is not defined
I'm probably missing something obvious. Can anybody help?
Thanks!
You have to import ContentHandler in handlers.py as follows:
from xml.sax.handler import ContentHandler
This should do it.