0

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?

  • 2
    Have you checked for typos? Seems you have `foob` and `foop` coexisting together. – jlandercy May 16 '19 at 14:04
  • That's because I changed the names for this post. There are no typos in the real code. – Jeff White May 16 '19 at 14:07
  • I would recommend that you go through [How to write a python Module](https://stackoverflow.com/questions/15746675/how-to-write-a-python-module-package). –  May 16 '19 at 14:43

1 Answers1

0

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.

RibomBalt
  • 190
  • 8