Home > Software engineering >  class in a private/custom package is not callable when imported
class in a private/custom package is not callable when imported

Time:12-04

I have a git repo containing my custom python package. I install it using pip

pip install git https://github.com/xxxx/my-package.git

The package name is mytest the code is under src/mytest and it contains 3 files

simple.py
def add_one(number):
    return number   1

hard.py
def add_one(number):
    return number   1

myclass.py
class MyClass:
    def __init__(self, something):

I open a python shell and I type

from mytest import simple, hard
simple.add_one(1)
hard.add_one(1)

so far so good, then I run into trouble using MyClass

from mytest import MyClass

mportError: cannot import name 'MyClass' from 'mytest' 

why does it work with simple functions and not a class? What am I missing?

CodePudding user response:

You are trying to import the class directly from the package instead of the (sub-)module. You want:

from mytest import myclass 

Then you can instantiate with the myclass namespace, i.e.

kls = myclass.MyClass(...)

Same as with your functions

Alternatively, if you want to reference MyClass directly you can use

from mytest.myclass import MyClass
kls = MyClass(...)
  • Related