Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 ?

like image 831
pierocampanelli Avatar asked Jul 17 '10 14:07

pierocampanelli


1 Answers

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!

like image 174
Alex Martelli Avatar answered Oct 10 '22 23:10

Alex Martelli