rdodev
rdodev

Reputation: 3192

General Python modules

I see this question has been asked before, but I still trying to get my head around working with python modules. My app has a very basic structure:

app/
   __init__.py
   driver.py
   dbloader/
     __init__.py
     loader.py

both __init__.py files are empty. driver.py only has one class Driver() and loader.py has only class in it Loader()

So, to test this setup, cd to inside the app/ directory. From here I start a python shell. I then try:

import dbloader which works (i.e. no errors). However, I've tried every permutation to get to instantiate Loader() inside loader.py to no avail. A few ones of the ones I've tried are:

from dbloader import loader
from dbloader.loader import Loader

I've also tried

importing just dbloader and then trying to instantiate as follow:

import dbloader
l = dbloader.Loader()

All to no avail. I believe reading elsewhere that the current directory and subdirectories are automatically included in the pythonpath when executing the python shell (is this true?)

Anyhow, any assistance would be much appreciated.

Upvotes: 2

Views: 365

Answers (3)

Casey Kuball
Casey Kuball

Reputation: 7965

In addition to using the solution proposed by Daenyth and Daniel Roseman, you can access Loader directly from dbloader, if you from-import Loader in dbloader:

# app/dbloader/__init__.py
from dbloader.loader import Loader

Then, in your shell:

import dbloader
l = dbloader.Loader()

# or...

from dbloader import Loader
l2 = Loader()

This is a nice solution for cleaning up namespaces.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599866

dbloader by itself doesn't have any reference to the Loader class. However you do it, you need to go through the loader namespace. So, two possible ways:

from dbloader import loader
l = loader.Loader()

or

from dbloader.loader import Loader
l = Loader()

It helps to think about namespaces, rather than modules or classes. Loader is in the dbloader.loader namespace, and to have access to that class you either need to import the class itself, or the module that contains it, into your current namespace.

Upvotes: 3

Daenyth
Daenyth

Reputation: 37461

import X adds X to your namespace.

import dbloader - This adds the module dbloader. You'd get to your class with dbloader.loader.Loader

from dbloader import loader - This adds the module loader to your namespace. You'd access your class with loader.Loader.

from dbloader.loader import Loader - This imports the class Loader to your namespace. You'd just use Loader() here.

Try playing around in the python shell with dir and help, you should be able to understand the structure a little better then.

Upvotes: 2

Related Questions