Skip to content
Advertisement

Python Package Creation

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

Package/
    __init__.py
    Part1/
        __init__.py
        item.py
        load_items.py
    Part2/
        __init__.py
        section.py
    Part3/
        __init__.py
        mappings/
            file1.txt
            file2.txt
            ...
            file10.txt
        map.py
        unmapped.txt

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

import Package
print(dir(Package))

The output from this is

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']

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

print(Package.Part1)

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 :

class Person:
  name = "John"

  def foo(self):
        return "Hello"

print(dir(Person))

>> out 
    [... 'foo', 'name']

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

import os
os.listdir(path)

You can retrieve the path of an installed package with importlib

Here is an example with the requests package

import importlib.util
path = importlib.util.find_spec("requests").origin

>> out : 
    ..../python3.7/site-packages/requests/__init__.py'

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

import importlib.util
import os

path = importlib.util.find_spec("requests").origin

# remove the "/__init__.py" part
path = path[:-11]
os.listdir(path)

>> out : 
    ['cookies.py',
     'auth.py',
     'sessions.py',
      ...
     ]

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