Eugene
Eugene

Reputation: 143

Can't Import Python Class

I am having an issue with Python imports. I created a module to conveniently import a few classes inside of the module with a single statement. I put all of my imports inside of the init of that module, but it doesn't seem to work.

maindir\
- driver.py
- Utility\
  - __init__.py
  - UtilityClasses.py

My folder structure looks like the above. Inside of UtilityClasses I have one a class that I have created called MyClass.

Inside of the init file in the Utility folder, I have code that says:

import UtilityClasses
from UtilityClasses import MyClass

Inside of driver.py I have code that says:

import Utility
myVar = MyClass(param1)

However, when I run this, I get an error telling me that name MyClass is not defined.

Upvotes: 2

Views: 21915

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 881575

Your code

import Utility
myVar = MyClass(param1)

of course won't work -- MyClass is nowhere mentioned and it won't come magically from nowhere. Explicit is better than implicit:

from Utility import MyClass
myVar = MyClass(param1)

should work like a charm!

Upvotes: 2

Kedar
Kedar

Reputation: 1698

In __init__.py, you can do

from UtilityClasses import *
from SomeOtherFile import *

This will import everything from UtilityClasses.py and SomeOtherFile.py.

But you still have to access it using the module name

Update: You can access everything like this

In driver.py:

from Utility import *

a = MyClass()
b = ClassInSomeOtherFile()

Upvotes: 4

Related Questions