如何在开发 Python 包时缩短导入语句?

How to shorten import statements while developing a Python package?

我正在设计一个 Python 包。请看下面的项目结构-

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

以下是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='abc@example.com',
      license='MIT',
      packages=find_packages(),
      zip_safe=False,
      )

使用python setup.py即可成功安装上述包。但是,为了使用这个包,我需要编写如下所示的长 import 语句-

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

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

如您所见,存在以下两个问题-

  1. 第一次导入,即 from android_py.android import Android 太长了,不方便记忆。我认为像 import android 这样更短的东西更好。
  2. 第二次导入,即from android_py.options import Power比较麻烦。它应该在第一次导入时自动导入。

能否建议我如何重新配置​​此软件包以克服上述问题?请注意,我使用的是 Python 2.7(如果重要的话)!

这是您要找的吗? https://python-packaging.readthedocs.io/en/latest/everything.html

编辑:使用 link 中的代码,我能够做到这一点:

import funniest.funniest
import types

print(dir(funniest))

print([getattr(funniest, a) for a in dir(funniest)
    if isinstance(getattr(funniest, a), types.FunctionType)])

print(funniest.funniest.joke())

print("works")

这会调用 ./python-packaging-master/funniest/funniest/init.py 中的 joke()

只需更改示例中的文件夹结构,即可直接调用import funniest

我相信您可以将同样的东西应用到您的包裹中。

除了我的评论之外,我将尝试举一个简短的例子。假设你有一个 power.py:

class Power:
   On = True 

在同一个包中 android.py:

from . import power

class Android:
    Power = power.Power

在android_py包中__init__.py:

from .android import Android

现在,从你的 app.py、main.py 或任何你能做到的地方:

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

顺便说一句:我对包名 android_py 不是很满意。同样命名为android,一个包android里面有一个android.py是没有问题的。或者在路径名中解释:有android/android.py是没有问题的。使用上面示例中 android.py__init__.py 中使用的相对导入 . 它应该可以工作。