Importing a subclass where it is under a package: ModuleNotFoundError - python

./package/test.py is working smoothly. I am expecting ./test.py would work smoothly just like that, but I am getting this running ./test.py:
Traceback (most recent call last):
File "test.py", line 2, in <module>
from package.subclass import Subclass
File ".../package/subclass.py", line 1, in <module>
from subclass import Subclass
ModuleNotFoundError: No module named 'subclass'
It is able to import class1. When it reads the 1st line of the subclass, it gives ModuleNotFoundError.
I have tried with ./package/__init__.py, a empty one gives the same error as above. When I have proper imports in ./package/__init__.py, the error becomes not being able to even find class1 in line 1 of __init__.py.
File directory as below:
./package/class1.py
./package/class2.py
./package/subclass.py
./package/test.py
./test.py
Code:
# ./package/class1.py
class Class1():
...
# ./package/class2.py
class Class2():
...
# ./package/subclass.py
from class2 import Class2
class Subclass(Class2):
...
# ./package/test.py
from class1 import Class1
from subclass import Subclass
...
# ./test.py
from package.class1 import Class1
from package.subclass import Subclass
...

Setting PYTHONPATH could be an option. Alternatively, given your current structure:
#subclass.py
from .class2 import Class2
class Subclass(Class2):
pass
#package/test.py
from .class1 import Class1
from .subclass import Subclass
#test.py
from package.class1 import Class1
from package.subclass import Subclass
To run test.py, simply run python test.py or python -m test
To run package/test.py, you will have to use python -m package.test

Try adding an empty __init__.py to the directory
The __init__.py tells the python interpreter that the directory it is dealing with is actually a module.
Hope this helps!

Aside from proper __init__.py, you'll also need to use:
from package.class1 import Class1
from package.subclass import Subclass
Note the added package.. Just a dot would also work, as that would be a relative import.

Related

ModuleNotFoundError when using a function from a custom module that imports another custom module

I have a folder structure similar to this (my example has all the necessary bits):
web-scraper/
scraper.py
modules/
__init__.py
config.py
website_one_scraper.py
Where config.py just stores some global variables. It looks a bit like:
global var1
var1 = "This is a test!"
Within website_one_scraper.py it looks like this:
import config
def test_function():
# Do some web stuff...
return = len(config.var1)
if __name__ == "__main__":
print(test_function)
And scraper.py looks like this:
from module import website_one_scraper
print(website_one_scraper.test_function())
website_scraper_one.py works fine when run by itself, and thus the code under if __name__ == "__main__" is run. However, when I run scraper.py, I get the error:
ModuleNotFoundError: No module named 'config'
And this is the full error and traceback (albeit with different names, as I've changed some names for the example above):
Traceback (most recent call last):
File "c:\Users\User\Documents\Programming\Work\intrack-web-scraper\satellite_scraper.py", line 3, in
<module>
from modules import planet4589
File "c:\Users\User\Documents\Programming\Work\intrack-web-scraper\modules\planet4589.py", line 5, in
<module>
import config
ModuleNotFoundError: No module named 'config'
Also note that In scraper.py I've tried replacing from modules import website_one_scraper with import website_one_scraper, from .modules import website_one_scraper, and from . import website_one_scraper, but they all don't work.
What could the cause of my error be? Could it be something to do with how I'm importing everything?
(I'm using Python 3.9.1)
In your website_scraper_one.py, instead of import config.py try to use from . import config
Explanation:
. is the current package or the current folder
config is the module to import

Python wont allow me to import .py files from same directory

So I'm just starting to learn Python, and I am learning classes and imports, but for some reason even when I follow the same code as my book say to do, I get a traceback error.
Traceback (most recent call last):
File "C:/Users/Programming/Desktop/Programs/EX40/main.py", line 1, in <module>
import objects.py
ModuleNotFoundError: No module named 'objects.py'; 'objects' is not a package
Here is both my Python files in which I'm trying to link:
main.py
import objects.py
print(MyStuff.tangerine)
objects.py
class MyStuff(object):
def __init__(self, arm):
self.tangerine = 'And now a thousand years between'
self.arm = arm
def apple(self):
print('I AM CLASSY APPLES!')
Try using
import objects
Because it takes py as a module in the objects file which does not exist
import objects.py is not a valid import
https://docs.python.org/3/reference/import.html
Try
from objects import MyStuff
Instantiating the class:
mystuff = MyStuff("arm value")
print(mystuff.tangerine)

Creating importable Python 3 package / module

I am having trouble creating an importable Python package/library/module or whatever the right nomenclature is. I am using Python 3.7
The file structure I am using is:
Python37//Lib//mypackage
mypackage
__init__.py
mypackage_.py
The code in __init__.py is:
from mypackage.mypackage_ import MyClass
The code in mypackage_.py is:
class MyClass:
def __init__(self, myarg = None):
self.myvar = myarg
And from my desktop I try running the following code:
import mypackage
x = MyClass(None)
But get the following error:
Traceback (most recent call last):
File "C:\Users\***\Desktop\importtest.py", line 3, in <module>
x = MyClass(None)
NameError: name 'MyClass' is not defined
You haven't imported the name MyClass into your current namespace. You've imported mypackage. To access anything within mypackage, you need to prefix the name with mypackage.<Name>
import mypackage
x = mypackage.MyClass(None)
As #rdas says, you need to prefix the name with mypackage.<Name>.
I don't recommend doing this, but you can wildcard import in order to make x = MyClass(None) work:
from mypackage import *
Now, everything from mypackage is imported and usable in the current namespace. However, you have to be careful with wildcard imports because they can create definition conflictions (if multiple modules have the same name for different things).

Error when importing python module from folders

I have a following directory structure:
source
source_1.py
__init__.py
source1.py has class Source defined
source1.py
class Source(object):
pass
I am able to import using this
>>> from source.source1 import Source
>>> Source
<class 'source.source1.Source'>
However when trying to import using the below method it fails.
>>> from source import *
>>> source1.Source
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'source1' is not defined
Please let me know how can we use the 2nd import ?
For importing from a package (unlike importing from a module) you need to specify what * means. To do that, in __init__.py add a line like this:
__all__ = ["source1"]
See the Python documentation for Importing * From a Package.

Python : Cannot find any functions within my own module?

I have created my own module with filename mymodule.py. The file contains:
def testmod():
print "test module success"
I have placed this file within /Library/Python/2.7/site-packages/mymodule/mymodule.py
I have also added a __init__.py file, these have compiled to generate
__init__.pyc and mymodule.pyc
Then in the python console I import it
import mymodule
which works fine
when I try to use mymodule.testmod() I get the following error:
AttributeError: 'module' object has no attribute 'testmod'
So yeah it seems like it has no functions?
You have a package mymodule, containing a module mymodule. The function is part of the module, not the package.
Import the module:
import mymodule.mymodule
and reference the function on that:
mymodule.mymodule.testmod()
You can use from ... import and import ... as to influence what gets imported exactly:
from mymodule import mymodule
mymodule.testmod()
or
from mymodule import mymodule as nestedmodule
nestedmodule.testmod
or
from mymodule.mymodule import testmod
testmod()
etc.

Categories