开发者

API of a package in python. In __init__.py? [closed]

Closed. This question is opinion-based. It is not currently accepting answers. 开发者_如何学C

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 4 years ago.

Improve this question

I have written a python package which consists of several .py files which contain classes and so on. I want to expose it to client using "Facade" pattern. So I don't want clients to learn all internal classes but only methods exposed by this API interface.

Question is: where do I put this api ? Do I define a file api.py inside the package or can I put this api in the __init__.py of the package?

I explain better with an example

<my_module>\
     __init__.py
     core.py
     submodule1.py
     submodule2.py
     util.py
     ........

so where do I put the public API of ?


The most common choice is to use __init__.py -- it's worth hiving off to a module of its own (or more) only if it's complex enough to warrant it (then it wouldn't be much of a Facade;-) or, more importantly, if you provide alternative APIs (a simplified one with reduced functionality but greater ease of use, and a rich/complex one, for example), in which case using separate modules keeps things better organized.

To communicate to package users that they're not supposed to import other modules directly, be sure to name your "private, internal implementation modules" with a leading underscore: _core.py, not core.py, and so forth. This convention is always used in Python to separate public APIs from internal implementation details and is well worth the (really small) effort for you to implement it!


The __init__.py file is an acceptable place to put the public API or a package, with the other modules within it providing the implementation.


There are disadvantages to putting the api into __init__.py:

  • there is danger of causing cycling dependencies
  • it is not a obvious place to look when browsing a code base

Putting the api in a dedicated module like api.py elevates these issues. Furthermore, there are advantages like:

  • you can offer another api later in a second module (simplified, different use case etc.)
  • big Python projects like Enthought traits.api and Trac trac.api use this pattern
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜