Your constructor sets self.prevNode to None, and later you try to access node.prevNode.label, which is like trying to access None.label. None doesn't have any attributes, so trying to access any will give you an AttributeError.

Answer from Sven Marnach on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 74394435 › python-class-attributeerror-even-though-i-have-that-attribute
Python class attributeError, even though I have that attribute - Stack Overflow
If you rearrange the order of the lines in __init__ so that you define vel before (indirectly) trying to use it, that error will go away. ... Sign up to request clarification or add additional context in comments. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... I’m Jody, the Chief Product and Technology Officer at Stack Overflow.
Top answer
1 of 3
16

AttributeError typically identifies the missing attribute. e.g.:

class Foo:
    def __init__(self):
        self.a = 1

f = Foo()
print(f.a)
print(f.b)

When I run that, I see:

$ python foo.py
1
Traceback (most recent call last):
  File "foo.py", line 10, in <module>
    print(f.b)
AttributeError: Foo instance has no attribute 'b'

That's pretty explicit. If you're not seeing something like that, please post the exact error you're seeing.

EDIT

If you need to force the printing of an exception (for whatever reason), you can do this:

import traceback

try:
    # call function that gets AttributeError
except AttributeError:
    traceback.print_exc()

That should give you the full error message and traceback associated with the exception.

2 of 3
3

The traceback should alert you to the attribute access that raised the AttributeError exception:

>>> f.b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no attribute 'b'

Alternatively, convert the Exception to str:

>>> try:
...     f.b
... except AttributeError, e:
...     print e
... 
Foo instance has no attribute 'b'

If you want to get a list of the attributes available on an object, try dir() or help()

>>> dir(f)
['__doc__', '__init__', '__module__', 'a']

>>> help(str)
Help on class str in module __builtin__:

class str(basestring)
 |  str(object) -> string
 |  
 |  Return a nice string representation of the object.
 |  If the argument is a string, the return value is the same object.
 |  
 |  Method resolution order:
 |      str
 |      basestring
 |      object
 |  
 |  Methods defined here:
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
[...]
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

You can even call help() on dir (why is left as an exercise for the reader):

>>> help(dir)
Help on built-in function dir in module __builtin__:

dir(...)

dir([object]) -> list of strings

If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
  for a module object: the module's attributes.
  for a class object:  its attributes, and recursively the attributes
    of its bases.
  for any other object: its attributes, its class's attributes, and
    recursively the attributes of its class's base classes.

Failing these... you could always look at the code, unless you've been provided some precompiled module by a third-party, in which case you should demand better documentation (say some unit tests!) from your supplier!

🌐
Stack Apps
stackapps.com › questions › 3951 › attribute-error-while-using-the-stackoverflow-api-wrapper-for-python-on-idle
feature request - Attribute error while using the stackoverflow api wrapper for python on IDLE - Stack Apps
February 27, 2013 - But running it in IDLE gives the following error: Traceback (most recent call last): File "C:\Users\Animesh\Desktop\NLP\metastack.py", line 3, in <module> from stackexchange import Site, StackOverflow File "C:\Users\Animesh\Desktop\stackexchange.py", line 4, in <module> AttributeError: 'module' object has no attribute 'StackOverflow'
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 52695716 › getting-this-attribute-error-over-and-over-in-python
class - Getting this "Attribute error" over and over in python - Stack Overflow
Your class hasn't got the tours attribute, it has only got the _tours attribute. Maybe you want to use it instead. Remember that, in Python, if an attribute name starts with an underscore, it means that the attribute should be private and not ...
🌐
Stack Overflow
stackoverflow.com › questions › tagged › attributeerror
Newest 'attributeerror' Questions - Stack Overflow
I have an xml file with experimental data that I am trying to read out in Python with pandas. The data is separated into 2 experiments, which each have 2 wavelengths (and more subnodes). I can select ... ... I have dicom files from different sources and sometimes i get error like this: AttributeError: 'FileDataset' object has no attribute 'PatientAge' because some files doesn't have this attribute.
🌐
Stack Overflow
stackoverflow.com › questions › 65573930 › how-do-i-fix-the-attribute-error-in-python
graphics - How do I fix the attribute error in python? - Stack Overflow
i saved the graphics.py in its own folder called "graphics" in the Lib folder of the python program. the problem is that the GraphWin attribute can't be executed. however, if i double-click the same graphics file it runs normally. also, i tried ...
🌐
Stack Overflow
stackoverflow.com › questions › 23444697 › how-can-i-fix-this-attribute-error
python - How can I fix this attribute error? - Stack Overflow
You also have an extra ' in your code. ... Please see the SQLFORM documentation about how you create the form. I assume you've changed the code before you posted it up here, since python wouldn't compile it because of the = in the parameter ...
🌐
Real Python
realpython.com › ref › builtin-exceptions › attributeerror
AttributeError | Python’s Built-in Exceptions – Real Python
Every Python object will raise an AttributeError when you attempt to access a non-existent attribute on it. When you need to implement custom logic, then you can edit .__getattr__() accordingly before raising the error manually:
🌐
Carleton University
cs.carleton.edu › cs_comps › 1213 › pylearn › final_results › encyclopedia › attributeError.html
Error Encyclopedia | Attribute Error
Here we see that Python has returned an AttributeError. What it says is that our int type object “8” doesn’t have the ability to append. In PyLearn, the error message you’d see would look like the following:
Top answer
1 of 3
9

Attributes are properties of functions or classes or modules, and if a property is not found then it raises attribute error.

NameError are related to variables.

>>> x=2
>>> y=3
>>> z    #z is not defined so NameError

Traceback (most recent call last):
  File "<pyshell#136>", line 1, in <module>
    z
NameError: name 'z' is not defined

>>> def f():pass

>>> f.x=2 #define an attribue of f
>>> f.x
2
>>> f.y   #f has no attribute named y

Traceback (most recent call last):
  File "<pyshell#141>", line 1, in <module>
    f.y
AttributeError: 'function' object has no attribute 'y'

>>> import math   #a module  

>>> math.sin(90) #sin() is an attribute of math
0.8939966636005579

>>> math.cosx(90)  #but cosx() is not an attribute of math

Traceback (most recent call last):
  File "<pyshell#145>", line 1, in <module>
    math.cosx(90)
AttributeError: 'module' object has no attribute 'cosx'
2 of 3
2

From the docs I think the text is pretty self explanatory.

NameError Raised when a local or global name is not found. This applies only to unqualified names. The associated value is an error message that includes the name that could not be found.

AttributeError Raised when an attribute reference (see Attribute references) or assignment fails. (When an object does not support attribute references or attribute assignments at all, TypeError is raised.)

In you example above the reference to z raises NameError as you are trying to access an unqualified name (either local or global)

In you last example math.cosx is a dotted access (attribute reference) in this case is an attribute of the math module and thus AttributeError is raised.

🌐
Python
docs.python.org › 3 › library › exceptions.html
Built-in Exceptions — Python 3.14.4 documentation
Also, the filename2 constructor argument and attribute was added. ... Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for integers (which would rather raise MemoryError than give up).
Top answer
1 of 2
2

You can check if required message is in exception string.

except AttributeError as e:
    if "'product.product' object has no attribute 'order_line'" not in str(e):
        raise

But this is not recommended as you shouldn't be checking for attributes based of messages which can change in future.

Better approach would be to check if the attribute is present using hasattr

if hasattr(product.product, 'order_line'):
   # Do your stuff
2 of 2
2

As a general rule, try blocks should be as short as possible to make sure you only catch the expected exception. IOW, instead of:

try:
   func_that_may_raise_attributeerror(obj)
   print(obj.attr_that_may_not_exist)
   other_function_that_may_also_raise_an_unrelated_attribute_error(obj)
   print(obj.another_attr_that_may_not_exist)
   and_yet_another_one(obj)
except AttributeError as e:
   # oops, who raised the exception and for which attribute ???

You should have something like:

try:
    val = obj.attr_that_may_not_exists
except AttributeError as e:
    # handle the case here
else:
    do_something_with_val(val)

Note that for function calls etc, you can add proper try/except blocks around the access to "attribute that may not exists" in the function itself and raise a custom exception (eventually with more context infos - ie the object and attribute - as exception arguments) instead of a generic AttributeError.

Now for your own use case, as mentionned by poke in a comment, the proper solution is to set product.product.order_line to None (or any other sentinel value) instead of deleting the attribute. While it is technically legal to dynamically add or delete attributes in Python, this should definitly not be done on attributes that are part of the class public interface - those attributes should always exists for the whole object's lifetime.