lpares12
lpares12

Reputation: 4003

Import classes from child directory python

I've been trying to import some python classes which are defined in a child directory. The directory structure is as follows:

workspace/
    __init__.py
    main.py
    checker/
       __init__.py
       baseChecker.py
       gChecker.py

The baseChecker.py looks similar to:

import urllib
class BaseChecker(object):
    # SOME METHODS HERE

The gChecker.py file:

import baseChecker # should import baseChecker.py
class GChecker(BaseChecker): # gives a TypeError: Error when calling the metaclass bases
    # SOME METHODS WHICH USE URLLIB

And finally the main.py file:

import ?????
gChecker = GChecker()
gChecker.someStuff() # which uses urllib

My intention is to be able to run main.py file and call instantiate the classes under the checker/ directory. But I would like to avoid importing urllib from each file (if it is possible).

Note that both the __init__.py are empty files.

I have already tried calling from checker.gChecker import GChecker in main.py but a ImportError: No module named checker.gChecker shows.

Upvotes: 3

Views: 226

Answers (1)

saloua
saloua

Reputation: 2493

In the posted code, in gChecker.py, you need to do

from baseChecker import BaseChecker

instead of import baseChecker Otherwise you get

NameError: name 'BaseChecker' is not defined

Also with the mentioned folders structure you don't need checker module to be in the PYTHONPATH in order to be visible by main.py Then in main.y you can do:

from checker import gChecker.GChecker

Upvotes: 2

Related Questions