简体   繁体   中英

Python Custom package import module name not importing on init

I'm creating a custom package with the following structure:

test_package
    │   README.md
    │   setup.py
    │
    ├───my_package
    │       my_package.py
    │       __init__.py
    │
    └───tests
            tests.py

When importing my_package , I have to use

from my_package.my_package import my_class

o = my_class()

Or

import my_package

my_package.my_package.my_class()

How can I use just from my_package import my_class WITHOUT adding imports to __init__.py ? I can't do that because my package has dependency on pygdbmi .

I'm using setuptools.

Many thanks!!

import setuptools
import my_package

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    # Project information
    name=my_package.__title__,
    version=my_package.__version__,
    long_description_content_type="text/markdown",
    packages=setuptools.find_packages(),
    install_requires=["pygdbmi"],
    python_requires='>=3.7',
    # Tests
    test_suite='tests'
)

__init__.py :

__version__ = '0.0.1'
__title__ = 'my_package'

my_package.py

from pygdbmi.gdbcontroller import GdbController

class my_class:
    def __init__(self):
        print("my_class!!")
        self.gdbmi = GdbController()

tests.py :

import unittest

from my_package.my_package import my_class

class some_test(unittest.TestCase):
    def test_constructor(self):
        self.assertIsNotNone(my_class())

if __name__ == '__main__':
    unittest.main()

To illustrate my comment,

my_package.py :

from pygdbmi.gdbcontroller import GdbController

__version__ = '0.0.1'
__title__ = 'my_package'

class my_class:
    def __init__(self):
        print("my_class!!")

setup.py :

# ...

setuptools.setup(
    # Project information
    name=my_package.__title__,
    version=my_package.__version__,
    long_description_content_type="text/markdown",
    py_modules=['my_package'],  # replaces `packages=setuptools.find_packages(),`
    install_requires=["pygdbmi"],
    python_requires='>=3.7',
    # Tests
    test_suite='tests'
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM