Skip to content
Advertisement

Python Package Creation

I have a package i am trying to create. The directory hierarchy looks like this.

JavaScript

I have some other file main.py that is not in the package and inside I have put

JavaScript

The output from this is

JavaScript

however I was expecting to see “Part1”, “Part2”, and “Part3” in this list. I also tried

JavaScript

and I got an attribute error: Package has no attribute Part1.

This is the first package I have made and I am also unsure why __init__.py is needed in every directory? Or perhaps this is wrong and it isn’t. I’ve read a bunch of the other questions on stack overflow but none of them have really helped me understand. Basically, I’m looking for whether my package is structured correctly and why when I do dir(Package) the parts of it are not listed.

Advertisement

Answer

dir return all variables and methodes of an object

for example :

JavaScript

If you want to list all directories and files in a directory, you can do

JavaScript

You can retrieve the path of an installed package with importlib

Here is an example with the requests package

JavaScript

By combining both method, we can list all directories of our package

JavaScript

The __init__.py is required in each directory. This file tells your python interpreter that the folder is a python package. Without it, you won’t be able to import the package in an other folder.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement