How to write a custom solution using a python package, modules etc
I am writing a packacge foobar which consists of the modules alice, bob, charles and david.
From my understanding of Python packages and modules, this means I will create a folder foobar, with the following subdirectories and files (please correct if I am wrong)
foobar/
__init__.py
alice/alice.py
bob/bob.py
charles/charles.py
david/david.py
The package should be executable, so that in addition to making the modules alice, bob etc available a开发者_高级运维s 'libraries', I should also be able to use foobar in a script like this:
python foobar --args=someargs
Question1:
Can a package be made executable and used in a script like I described above?
Question 2
The various modules will use code that I want to refactor into a common library. Does that mean creating a new sub directory 'foobar/common' and placing common.py in that folder?
Question 3
How will the modules foo import the common module ? Is it 'from foobar import common' or can I not use this since these modules are part of the package?
Question 4
I want to add logic for when the foobar package is being used in a script (assuming this can be done - I have only seen it done for modules)
The code used is something like:
if __name__ == "__main__":
dosomething()
where (in which file) would I put this logic ?
Can a package be made executable and used in a script like I described above?
Q1 and Q4. Yes, place your:
if __name__ == "__main__":
dosomething()
in foobar/__init__.py
Q2 The various modules will use code that I want to refactor into a common library. Does that mean creating a new sub directory 'foobar/common' and placing common.py in that folder?
No, you have to create foobar/common.py
, not foobar/common/common.py
. The same is true for all of your modules. Thus the right structure is:
foobar/
__init__.py
alice.py
bob.py
charles.py
common.py
david.py
Doing what you do you're creating package foobar
, subpackage alice
and module alice
in it, etc. That is not what you want as I understand. Furthermore it will not work at all, since a directory becomes a Python package if it contains __init__.py
in it, and you haven't created them in your subdirectories.
Q3 How will the modules foo import the common module ? Is it
from foobar import common
That's right. You can also simply use import common
however it can cause a conflict if your library will be used in a project that has it's own module/package named common
. So I prefer to use fully-qualified module names.
精彩评论