如何编写良好/正确的__init__.py包文件 [英] How do I write good/correct package __init__.py files

查看:83
本文介绍了如何编写良好/正确的__init__.py包文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的包裹具有以下结构:

My package has the following structure:

mobilescouter/
    __init__.py #1
    mapper/
        __init__.py  #2
        lxml/
            __init__.py #3
            vehiclemapper.py
            vehiclefeaturemapper.py
            vehiclefeaturesetmapper.py
        ...
        basemapper.py
   vehicle/
        __init__.py #4
        vehicle.py
        vehiclefeature.py
        vehiclefeaturemapper.py
   ...

我不确定如何正确编写__init__.py文件.
__init__.py #1看起来像:

I'm not sure how the __init__.py files should be correctly written.
The __init__.py #1 looks like:

__all__ = ['mapper', 'vehicle']
import mapper
import vehicle

但是例如__init__.py #2应该是什么样子?我的是:

But how should for example __init__.py #2 look like? Mine is:

__all__ = ['basemapper', 'lxml']
from basemaper import *
import lxml

何时应使用__all__?

推荐答案

__all__非常好-它有助于在不自动导入模块的情况下指导导入语句 http://docs.python.org/tutorial/modules.html #importing-from-a-package

__all__ is very good - it helps guide import statements without automatically importing modules http://docs.python.org/tutorial/modules.html#importing-from-a-package

使用__all__import *是多余的,只需要__all__

using __all__ and import * is redundant, only __all__ is needed

我认为在__init__.py中使用import *导入软件包的最强大的原因之一是能够重构已经增长为多个脚本的脚本而不会破坏现有的应用程序.但是,如果您从一开始就设计一个包装.我认为最好将__init__.py文件保留为空.

I think one of the most powerful reasons to use import * in an __init__.py to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py files empty.

例如:

foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo

然后应用程序会增长,现在它是一个完整的文件夹

then the app grows and now it's a whole folder

foo/
    __init__.py
    foofactories.py
    tallFoos.py
    shortfoos.py
    mediumfoos.py
    santaslittlehelperfoo.py
    superawsomefoo.py
    anotherfoo.py

然后初始化脚本可以说

__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
           'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo

以使编写用于执行以下操作的脚本在更改期间不会中断:

so that a script written to do the following does not break during the change:

from foo import fooFactory, tallFoo, shortFoo

这篇关于如何编写良好/正确的__init__.py包文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆