Python – How do I shorten import statements when developing Python packages?

How do I shorten import statements when developing Python packages?… here is a solution to the problem.

How do I shorten import statements when developing Python packages?

I’m designing a Python package. Take a look at the project structure below

android_py
├── README.md
├── setup.py
└── android_py
    ├── __init__.py
    ├── options.py
    └── android.py

Here's what setup.py

from setuptools import setup, find_packages

setup(name='android_py',
      version='0.1',
      description='The description goes here',
      url='http://github.com/example_user/android_py',
      author='Bob',
      author_email='[email protected]',
      license='MIT',
      packages=find_packages(),
      zip_safe=False,
      )

Using Python setup.py you can successfully install the above packages. However, in order to use this package, I need to write a long import statement like this-

from android_py.android import Android
from android_py.options import Power

my_robot = Android()
my_robot.set_power(Power.On)

As you can see, there are two problems –

  1. The first import, i.android_py.android import Android, is too long and user-friendly because it’s hard to remember. I think shorter things like import android are much better.
  2. The second import, from android_py.options import Power, is cumbersome. It should be imported automatically on the first import.

Could you please suggest how I can reconfigure this package to overcome the above issue? Note that I’m using Python 2.7 (if important)!

Solution

In addition to my comment, I will try to give a short example. Let’s say you have a power.py:

class Power:
   On = True 

There is a android.py in the same package:

from . import power

class Android:
    Power = power. Power

In the android_py package __init__.py:

from .android import Android

Now, from outside of your app.py, main.py or whatever you can:

from android_py import Android
my_robot = Android()
my_robot.set_power(my_robot. Power.On)

By the way: I’m not very happy with the package name android_py. Also named Android, having a android.py in the Android package is no problem. Or explain with a path name: there is no problem with android/android .py. Use relative imports in android.py and __init__.py in the example above . It should work.

Related Problems and Solutions