Private
Private

Reputation: 2694

How to avoid repetitive naming in python packages?

Say I am building a python project that models bananas, how would I structure it? I usually start with

mkdir bananas

then I code in bananas.py which is file until I start adding README, LICENSE, CONTRIBUTORS, and more and the python files are just lost in meta files. Then I do the same again

mkdir bananas
mv *.py* bananas

in order to have the actual code separated from the meta. Now I have a double, repetitive dir structure,

$ ls /path/to/bananas
README
LICENSE
CONTRIBUTORS
bananas/banana.py

So this ends up in

bananas/bananas/banana.py

This just feels wrong to me. The code I touch most is hidden away too far. Also I hate imports like

from bananas.bananas import Banana

I just want to do

from bananas import Banana

Any thoughts? What am I missing? I quote HGP:

Repetitive paths are confusing for both your tools and your developers. Unnecessary nesting doesn’t help anybody (unless they’re nostalgic for monolithic SVN repos).

Upvotes: 2

Views: 158

Answers (2)

Tagc
Tagc

Reputation: 9076

Personally I don't see any problem with structuring it like that, and it's what I've done in my own projects. It seems to be the recommended approach according to a few online guides I've tried following.

For instance, from Open Sourcing a Python Project the Right Way the author defines the structure of an example project:

$ pwd
~/code/sandman
$ tree
.
|- LICENSE
|- README.md
|- TODO.md
|- docs
|   |-- conf.py
|   |-- generated
|   |-- index.rst
|   |-- installation.rst
|   |-- modules.rst
|   |-- quickstart.rst
|   |-- sandman.rst
|- requirements.txt
|- sandman
|   |-- __init__.py
|   |-- exception.py
|   |-- model.py
|   |-- sandman.py
|   |-- test
|       |-- models.py
|       |-- test_sandman.py
|- setup.py

So in this case you'd end up with a path like sandman/sandman/sandman.py.

Upvotes: 2

Harper04
Harper04

Reputation: 375

Sometimes this is unavoidable. Just look at the datetime module of the standard lib.

datetime.datetime datetime.datetime.today().date()

You can do relative imports. A file in bananas only has to do

from bananas import Banana  # or
from .bananas import Banana

Which is recommended anyway to make your module reusable by making it movable m)

Some folks import the module, not the class

from bananas import bananas as bananaModule
bananaModule.banana()

You could also give your project a fancy codename so it becomes:

from fancyish.bananas import bananas as bananaModule

Upvotes: 1

Related Questions