Why is my class not getting recognized by my Python package?

I am in the process of transforming my extensive Python script into a package. My file structure is as follows:

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

The lib/foob/__init__.py file contains a single defined class:

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

The bin/foob file includes:

import foob

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

get_nodes()

I am executing the script using the command:

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

Upon running, I encounter the following error:

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 appears similar to another program that functions correctly. What could be causing this issue?

Answer №1

The issue appears to be related to a Naming Conflict. You seem to be importing module bin/foob instead of lib/foob.

Python Import Order

When you use the import command, Python will search in the following order:

  1. Built-in Modules.
  2. Current Directory.
  3. Environment Variable: PYTHONPATH
  4. Other Directories (not relevant here).

You can view these directories by running import sys; sys.path


Since you are currently in bin/foob, this is what you are importing. Confirm this by using import os; os.getcwd().

I suggest avoiding using the same names to prevent conflicts.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error importing Matplotlib and Pylab libraries

Having a tough time trying to figure this out all day, looking for some help... I'm using python 2.7, installed matplotlib but encountering errors when trying to import pylab. It keeps saying that the module is not found, even though there is a pylab ...

Error caused by incorrect syntax in Python MySQL query, even though syntax appears to be correct

I'm currently working on verifying the existence of a specific record with an id. Previously, everything was running smoothly, but now I am encountering an error indicating that my syntax is incorrect. Here is the syntax causing the issue: cursor.exe ...

Issue: joining the list of available PIL interpolation methods is not working as expected

During the training of an image classification model, I encountered a persistent error that interrupts the process. view the image representation here ...

Python Selenium - NoSuchDriverException: Error occurred while trying to locate chromedriver using Selenium Manager

Encountering an issue while attempting to create an object with Selenium Webdriver: selenium.common.exceptions.NoSuchDriverException: Message: Unable to obtain chromedriver using Selenium Manager; Message: Unsuccessful command executed: Z:\Python 3.9. ...

Retrieving parameters from the query string in Python

When calling this URL, I need to pass a query string parameter named 'name' to details.py The URL is: http://www.somesite.com/details.py?name=test I attempted to retrieve this parameter using the request method but was unsuccessful. Code sn ...

Incorporating voting functionality into Django objects

Currently, I am facing a challenge with multiple 'Photo' objects being displayed on a page template. Within the Photo Model, there is a field called 'score' which defaults to 0. I am having difficulty figuring out how to implement two ...

The uncomplicated Python script encountered an endless loop

I am currently working on a basic XOR program. After double-checking my syntax, I executed the program and unexpectedly encountered an infinite loop. I have been unable to identify the cause of this issue. Can anyone provide assistance? def disencode(n) ...

What sets BeautifulSoup apart from Scrapy crawler?

Looking to create a website that compares prices of products on Amazon and eBay. Which platform would be more effective for this task, and why? I have some knowledge about BeautifulSoup but am not very familiar with Scrapy crawler. ...

The ScrollableLabel does not respond to scrolling commands

My ScrollableLabel is not scrolling as expected, even though the text displays properly. I followed Sentdex's example code but still can't figure out where I went wrong. Apologies if this is a simple question. class ScrollableLabel(ScrollVi ...

Using NLTK for natural language processing, the task involves sorting through a list of lists by filtering based on the first two elements in each sublist

After executing the following code, I was able to obtain a list of trigrams along with their frequencies using NLTK. tokens = nltk.wordpunct_tokenize(docs) from nltk.collocations import * trigram_measures = nltk.collocations.TrigramAssocMeasures() finderT ...

Using Django to load a template and incorporate a loading spinner to enhance user experience during data retrieval

In my Django project, I need to load body.html first and then dashboard.html. The dashboard.html file is heavy as it works with python dataframes within the script tag. So, my goal is to display body.html first, and once it's rendered, show a loading ...

Python threading - Unable to assign parent, the new parent belongs to another thread

Looking to create a dynamic GUI feature where pressing a button updates a scrollArea on-the-fly without locking the interface. Attempted using QThread to ensure smooth operation and visual feedback during population of the scrollArea elements. Implemente ...

What could be causing the error of a missing required positional argument even though it appears to be provided as required?

Currently, I am in the process of creating a boid program using Python. This project involves two separate programs - "boid.py" which defines the boid class and "flocking practice.py" which is intended to utilize this class and display the boids on the scr ...

`Why do I keep encountering viewport issues with Ajax in Django?`

In my current project, I am exploring the use of Ajax to validate whether a specific field value already exists in the database. Within my urls.py file: #App Auxiliares_Tipos: path('ajax/validar_tipaux/', validar_tipaux), path('Tipos_de_au ...

For some odd reason, my stack is missing the "top" attribute

import random value = { "Two":2,"Three":3, "Four":4, "Five":5, "Six":6, "Seven":7, "Eight":8, "Nine":9, "Ten":10, "Jack":10, "Queen&qu ...

webdriver.support.select - Select fails to interact with the element

Hey there, I am encountering an issue with the select element below: <div class="col-xs-12 col-md-6"> <label class="ph_label pointer city"> <span class="l citylbl">City</span> <select class="cities custom-dropdown" data-validati ...

Generating a data set by combining various lists

Having just started with Python, I may be asking a basic question. I have two sets of lists, one containing volume names and associated counts. Here's a sample of the data: volumes1 = ['Shield', 'Side', 'expHall', &apos ...

The element was located, however, it was not activated, resulting in the test failing

While setting up an automated test on Amazon's website, I encountered an issue where I needed to navigate to the "sign up" page. The link to register is hidden in a menu that only appears when you hover over the sign-in link. After running a command i ...

Utilizing Ctypes to utilize TA-Lib, assistance with invoking functions

For the last few days, I've been grappling with integrating TA-Lib with Python. After compiling the source into a dylib file on my Mac and trying to call it from a Python script, here's the code snippet: from ctypes import * import numpy c_floa ...

Type-constrained mapping in Python with a touch of uniqueness

In my Python project, I am working on a simple message handling system. The concept is to have functions registered as message handlers based on the message type. Here is an example: class Message(Protocol): ... class M1(Message): ... def handler ...