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.
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.
As per the other answers (and the error message) you are accessing None.label. If it is expected that node might be None, then you will need to check for it before appending it.
while node.label != node.prevNode.label:
node = node.prevNode
if node is not None:
labels.append(node.label)
This happens because the scipy module doesn't have any attribute named sparse. That attribute only gets defined when you import scipy.sparse.
Submodules don't automatically get imported when you just import scipy; you need to import them explicitly. The same holds for most packages, although a package can choose to import its own submodules if it wants to. (For example, if scipy/__init__.py included a statement import scipy.sparse, then the sparse submodule would be imported whenever you import scipy.)
Because you imported scipy, not sparse. Try from scipy import sparse?
Videos
And what does that error generally mean?
An Attribute in Python is a name belonging to an object - a method or a variable. An AttributeError means that the program tried to use an attribute of an object, but the object did not have the requested attribute.
For instance, string objects have the 'upper' attribute, which is a method that returns the uppercase version of the string. You could write a method that uses it like this:
def get_upper(my_string):
return my_string.upper()
However, note that there's nothing in that method to ensure that you have to give it a string. You could pass in a file object, or a number. Neither of those have the 'upper' attribute, and Python will raise an Attribute Error.
As for why you're seeing it in this instance, you haven't provided enough detail for us to work it out. Add the full error message to your question.
1) Put code in Try ... Except block. get exception details.
2) Could you tell StackTrace details means which line # and method thrown error
And also are you able to run other simple python scripts without any error. Means just try to run some sample script etc.
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.
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!
As the argument of loadTestsFromTestCase, you're trying to access Boy.BoyTest, i.e., the BoyTest attribute of class object Boy, which just doesn't exist, as the error msg is telling you. Why don't you just use BoyTest there instead?
As Alex has stated you are trying to use BoyTest as an attibute of Boy:
class Boy:
def run(self, args):
print("Hello")
class BoyTest(unittest.TestCase)
def test(self)
self.assertEqual('2' , '2')
def self_test():
suite = unittest.TestSuite()
loader = unittest.TestLoader()
suite.addTest(loader.loadTestsFromTestCase(BoyTest))
return suite
Note the change:
suite.addTest(loader.loadTestsFromTestCase(Boy.BoyTest))
to:
suite.addTest(loader.loadTestsFromTestCase(BoyTest))
Does this solve your problem?
Your indentation is goofed, and you've mixed tabs and spaces. Run the script with python -tt to verify.
If you’re using python 3+ this may also occur if you’re using private variables that start with double underscore, e.g., self.__yourvariable. Just something to take note of for some of you who may run into this issue.
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'
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.
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
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.