I'm trying to convert my large Python script into a package. I have the following file structure:

bin/foob # The main Python script
lib/foob/__init__.py

The file lib/foob/__init__.py has one class defined:

class Node(object):
    def __init__(self):
        self.test = True

The file bin/foob has:

import foob

def get_nodes():
    x = foob.Node()

get_nodes()

I'm running the script with:

$ PYTHONPATH=PYTHONPATH:~/foob/lib ~/foob/bin/foob

The error I get is:

Traceback (most recent call last):
  File "/home/person/foob/bin/foob", line 6, in <module>
    x = get_nodes()
  File "/home/person/foob/bin/foob", line 4, in get_nodes
    node_obj = foob.Node()
AttributeError: module 'foob' has no attribute 'Node'

This structure seems identical to another program I wrote which works just fine. What am I missing?

1 Answers

0
Community On

I think the problem is Naming Conflict. You're importing module bin/foob rather than lib/foob.

Python Import Sequence

When you import something, the Python Interpreter would search in the following sequence:

  1. built-in Module.
  2. Current Directory.
  3. Environment Variable: PYTHONPATH
  4. Some other Directories.(irrelevant to this question)

the last three of which can be seen by import sys; sys.path


Seemingly you're in bin/foob, thus bin/foob is what you import. It can be checked by import os; os.getcwd().

I recommend you to avoid the same name.