创建python库:如何编写__init__.py

时间:2013-09-02 13:32:15

标签: python

我编写了一个小型Python库,目前托管在BitBucket。如您所见,该库名为pygpstools,它由5个文件组成:

  • gpstime.py→A类
  • satellite.py→A类
  • geodesy.py→带有一些大地测量方法的模块
  • almanacs.py→带有一些年历方法的模块
  • constants.py→一些常量

我想在自述文件中使用它。例如:

from pygpstools import GPSTime
GPSTime(wn=1751, tow=314880)

或:

import pygpstools
pygpstools.GPSTime(wn=1751, tow=314880)

但是在使用命令python setup.py install安装我的库之后,在尝试访问此类ImportError类时,我得到GPSTime

我猜问题出现在__init__.py文件中。当我在python IRC频道询问这个问题时,我被告知将它留空是有效的。但是我已经研究过,它看起来只是告诉Python它是一个模块,但它还不足以允许我正在寻找的这种导入,就像在那里的任何其他库一样。

所以我尝试过(目前没有在bitbucket上更新)将其用作__init__.py

__title__ = 'pygpstools'
__version__ = '0.1.1'
__author__ = 'Roman Rodriguez'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013 Roman Rodriguez'


import almanacs
import constants
import geodesy
import gpstime
import satellite

但仍无效:ImportError GPSTime

我错过了什么?

1 个答案:

答案 0 :(得分:4)

例如,

GPSTime位于模块gpstime中,因此其实际(相对)名称为gpstime.GPSTime。因此,当您在gpstime中导入__init__时,您实际上提供的名称为gpstime,其中包含对您的类型的引用为gpstime.GPSTime

因此您必须使用from pygpstools import gpstime然后gpstime.GPSTime作为类型名称。

显然这不是您想要的,所以相反,您希望在__init__模块中“收集”所有类型。你可以直接使它们可用来做到这一点:

from almanacs import *
from constants import *
from geodesy import *
from gpstime import GPSTime
from satellite import * 

我现在使用*导入任何内容,因为我没有仔细查看文件中的实际类型。你应该指定它。还建议您在__all__中定义__init__列表,以便在编写from pygpstools import *时控制导入的名称。