Меню

Nonetype object has no attribute append ошибка

I have a script in which I am extracting value for every user and adding that in a list but I am getting «‘NoneType’ object has no attribute ‘append'». My code is like

last_list=[]
if p.last_name==None or p.last_name=="": 
    pass
last_list=last_list.append(p.last_name)
print last_list

I want to add last name in list. If its none then dont add it in list . Please help
Note:p is the object that I am using to get info from my module which have all first_name ,last_name , age etc…. Please suggest ….Thanks in advance

LBes's user avatar

LBes

3,3161 gold badge31 silver badges61 bronze badges

asked Oct 15, 2012 at 11:35

learner's user avatar

0

list is mutable

Change

last_list=last_list.append(p.last_name)

to

last_list.append(p.last_name)

will work

Uma Madhavi's user avatar

Uma Madhavi

4,8215 gold badges37 silver badges73 bronze badges

answered Apr 29, 2017 at 7:18

jessiejcjsjz's user avatar

jessiejcjsjzjessiejcjsjz

1,7311 gold badge8 silver badges3 bronze badges

0

When doing pan_list.append(p.last) you’re doing an inplace operation, that is an operation that modifies the object and returns nothing (i.e. None).

You should do something like this :

last_list=[]
if p.last_name==None or p.last_name=="": 
    pass
last_list.append(p.last)  # Here I modify the last_list, no affectation
print last_list

answered Oct 15, 2012 at 11:52

Cédric Julien's user avatar

Cédric JulienCédric Julien

77.2k15 gold badges126 silver badges131 bronze badges

2

You are not supposed to assign it to any variable, when you append something in the list, it updates automatically.
use only:-

last_list.append(p.last)

if you assign this to a variable «last_list» again, it will no more be a list (will become a none type variable since you haven’t declared the type for that)
and append will become invalid in the next run.

Ru Chern Chong's user avatar

answered Jan 1, 2020 at 13:45

Jayesh Mishra's user avatar

I think what you want is this:

last_list=[]
if p.last_name != None and p.last_name != "":
    last_list.append(p.last_name)
print last_list

Your current if statement:

if p.last_name == None or p.last_name == "":
    pass

Effectively never does anything. If p.last_name is none or the empty string, it does nothing inside the loop. If p.last_name is something else, the body of the if statement is skipped.

Also, it looks like your statement pan_list.append(p.last) is a typo, because I see neither pan_list nor p.last getting used anywhere else in the code you have posted.

answered Oct 15, 2012 at 11:56

Joe Day's user avatar

Joe DayJoe Day

6,7354 gold badges24 silver badges26 bronze badges

1

If you attempt to call the append() method on a variable with a None value, you will raise the error AttributeError: ‘NoneType’ object has no attribute ‘append’. To solve this error, ensure you are not assigning the return value from append() to a variable. The Python append() method updates an existing list; it does not return a new list.

This tutorial will go through how to solve this error with code examples.


Table of contents

  • AttributeError: ‘NoneType’ object has no attribute ‘append’
  • Example
    • Solution
  • Summary

AttributeError: ‘NoneType’ object has no attribute ‘append’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘NoneType’ object has no attribute ‘append’” tells us that the NoneType object does not have the attribute append(). The append() method belongs to the List data type, and appends elements to the end of a list.

A NoneType object indicates no value:

obj = None
print(type(obj))
<class 'NoneType'>

Let’s look at the syntax of the append method:

list.append(element)

Parameters:

  • element: Required. An element of any type to append.

The append method does not return a value, in other words, it returns None. If we assign the result of the append() method to a variable, the variable will be a NoneType object.

Example

Let’s look at an example where we have a list of strings, and we want to append another string to the list. First, we will define the list:

# List of planets

planets = ["Jupiter", "Mars", "Neptune", "Saturn"]

planets = planets.append("Mercury")

print(planets)

planets = planets.append("Venus")

print(f'Updated list of planets: {planets}')

Let’s run the code to see what happens:

None
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      5 planets = planets.append("Mercury")
      6 
----≻ 7 planets = planets.append("Venus")
      8 
      9 print(f'Updated list of planets: {planets}')

AttributeError: 'NoneType' object has no attribute 'append'

The error occurs because the first call to append returns a None value assigned to the planets variable. Then, we tried to call append() on the planets variable, which is no longer a list but a None value. The append() method updates an existing list; it does not create a new list.

Solution

We need to remove the assignment operation when calling the append() method to solve this error. Let’s look at the revised code:

# List of planets

planets = ["Jupiter", "Mars", "Neptune", "Saturn"]

planets.append("Mercury")

planets.append("Venus")

print(f'Updated list of planets: {planets}')

Let’s run the code to see the result:

Updated list of planets: ['Jupiter', 'Mars', 'Neptune', 'Saturn', 'Mercury', 'Venus']

We update the list of planets by calling the append() method twice. The updated list contains the two new values.

Summary

Congratulations on reading to the end of this tutorial! The error AttributeError: ‘NoneType’ object has no attribute ‘append’ occurs when you call the append() method on a NoneType object. This error commonly occurs if you call the append method and then assign the result to the same variable name as the original list. The append() method returns None, so you will replace the list with a None value by doing this.

For further reading on AttributeErrors, go to the article: How to Solve Python AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’.

Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

The AttributeError: ‘NoneType’ object has no attribute ‘append’ error happens when the append() attribute is called in the None type object. The NoneType object has no attribute like append(). That’s where the error AttributeError: ‘NoneType’ object has no attribute ‘append’ has happened.

The python variables, which have no value initialised, have no data type. These variables are not assigned any value, or objects. These python variable does not support append() attribute. when you call append() attribute in a None type variable, the exception AttributeError: ‘NoneType’ object has no attribute ‘append’ will be thrown.

If nothing is assigned to the python variable, the variable can not be used unless any value or object is assigned. Calling the attribute of this variable value is pointless. If you call an attribute like append() the exception AttributeError: ‘NoneType’ object has no attribute ‘append’ will be thrown.

Exception

If python throws the attribute error, the error stack will be seen as below. The AttributeError: ‘NoneType’ object has no attribute ‘append’ error would display the line where the error happened.

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    a.append(' World')
AttributeError: 'NoneType' object has no attribute 'append'
[Finished in 0.0s with exit code 1]

How to reproduce this issue

If a python variable is created without assigning an object or value, it contains None. If the attribute is called with the python variable, the error will be thrown. The exception is thrown by calling an attribute from a variable that has no object assigned to it.

Program

a = None;
a.append(' World')
print a

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    a.append(' World')
AttributeError: 'NoneType' object has no attribute 'append'
[Finished in 0.0s with exit code 1]

Root Cause

The python class is a collection of data and functionality. The object in python is an enclosed collection of data and functionality identified as a class variable. The attribute in python is the collection of class-related data and functionality. These attributes are available for all class objects. The Attribute error is thrown if a variable has no object assigned is invoked.

The dot operator is used to reference to a class attribute. The reference attribute is made with an attribute that is not available in a class that throws the attribute error in python. The attribute is called in a variable that is not associated with any object of the class, which will also cause the attribute error AttributeError: ‘NoneType’ object has no attribute ‘append’.

Solution 1

The none type variable must be assigned with a value or object. If the variable has valid object that contains attributes such as append(), the error will be resolved. Otherwise, the variable is used with basic python operators such as arithmetic operator.

In the example below a variable contains a “Hello” string. Append method to concatenate with another “world” string is invoked In python, two strings are concatenated by using the arithmetic addition operator. This attribute error is fixed by replacing the append attribute with the arithmetic addition operator.

Program

a = 'Hello'
a = a +' World'
print a

Output

Hello World

Solution 2

If the python variable does not required to assign a value, the python variable should be assigned with empty list. The empty list will add a value if the append() function is called in the code. The example below contains a python variable that is assigned with an empty list. if the append() function is called, the value is added in the empty list.

Program

a = []
a.append(' World')
print a

Output

[' World']
[Finished in 0.0s]

Solution 3

Due to the dynamic creation of the variable the python variable may not be assigned with values. The datatype of the variable is unknown. In this case, the None data type must be checked before the an attribute is called.

Program

a = None;
if a is not None:
	a.append(' World')
print a

Output

None
[Finished in 0.1s]

Solution 4

The python variable should be validated for the expected data type. If the variable has the expected data type, then the object attribute should be invoked. Otherwise, the alternate flow will be invoked.

If the variable contains the excepted type of the value, the if block will execute. Otherwise, the else block will execute. This will eliminate the error AttributeError: ‘NoneType’ object has no attribute ‘append’.

Program

a = [];
if type(a) is list:
	a.append(' World')
else :
	a =a;
print a

Output

[' World']
[Finished in 0.0s]

Solution 5

If the data type of the variable is unknown, the attribute will be invoked with try and except block. The try block will execute if the python variable contains value or object. Otherwise, the except block will handle the error.

In the example below, the append attribute is called within the try block. If any error occurs the except block will be executed. The error will not be thrown.

Program

a = None;
try :
	a.append(' World')
except :
	print 'error';
print a

Output

error
Hello
[Finished in 0.0s]

The Python append() method returns a None value. This is because appending an item to a list updates an existing list. It does not create a new one.

If you try to assign the result of the append() method to a variable, you encounter a “TypeError: ‘NoneType’ object has no attribute ‘append’” error.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

In this guide, we talk about what this error means, why it is raised, and how you can solve it, with reference to an example.

TypeError: ‘NoneType’ object has no attribute ‘append’

In Python, it is a convention that methods that change sequences return None. The reason for this is because returning a new copy of the list would be suboptimal from a performance perspective when the existing list can just be changed.

Because append() does not create a new list, it is clear that the method will mutate an existing list. This prevents you from adding an item to an existing list by accident.

A common mistake coders make is to assign the result of the append() method to a new list. This does not work because append() changes an existing list. append() does not generate a new list to which you can assign to a variable.

An Example Scenario

Next, we build a program that lets a librarian add a book to a list of records. This list of records contains information about the author of a book and how many copies are available.

Let’s start by defining a list of books:

books = [
	{ "title": "The Great Gatsby", "available": 3 }
]

The books list contains one dictionary. A dictionary stores information about a specific book.  We add one record to this list of books:

books = books.append(
	{ "title": "Twilight", "available": 2 }
)

Our “books” list now contains two records. Next, we ask the user for information about a book they want to add to the list:

title = input("Enter the title of the book: ")
available = input("Enter how many copies of the book are available: ")

Now that we have this information, we can proceed to add a record to our list of books. We can do this using the append() method:

books = books.append(
	{ "title": title, "available": int(available) }
)

We’ve added a new dictionary to the “books” list. We have converted the value of “available” to an integer in our dictionary. We assign the result of the append() method to the “books” variable. Finally, we print the new list of books to the console:

Let’s run our code and see what happens:

Enter the title of the book: Pride and Prejudice
Enter how many copies of the book are available: 5
Traceback (most recent call last):
  File "main.py", line 12, in <module>
	books = books.append(
AttributeError: 'NoneType' object has no attribute 'append'

Our code successfully asks us to enter information about a book. When our code tries to add the book to our list of books, an error is returned.

The Solution

Our code returns an error because we’ve assigned the result of an append() method to a variable. Take a look at the code that adds Twilight to our list of books:

books = books.append(
	{ "title": "Twilight", "available": 2 }
)

This code changes the value of “books” to the value returned by the append() method. append() returns a None value. This means that “books” becomes equal to None.

When we try to append the book a user has written about in the console to the “books” list, our code returns an error. “books” is equal to None and you cannot add a value to a None value.

To solve this error, we have to remove the assignment operator from everywhere that we use the append() method:

books.append(
	{ "title": "Twilight", "available": 2 }
)

…

books.append(
	{ "title": title, "available": int(available) }
)

We’ve removed the “books = ” statement from each of these lines of code. When we use the append() method, a dictionary is added to books. We don’t assign the value of “books” to the value that append() returns.

Let’s run our code again:

Enter the title of the book: Pride and Prejudice
Enter how many copies of the book are available: 5
[{'title': 'The Great Gatsby', 'available': 3}, {'title': 'Twilight', 'available': 2}, {'title': 'Pride and Prejudice', 'available': 5}]

Our code successfully adds a dictionary entry for the book Pride and Prejudice to our list of books.

Conclusion

The “TypeError: ‘NoneType’ object has no attribute ‘append’” error is returned when you use the assignment operator with the append() method.

To solve this error, make sure you do not try to assign the result of the append() method to a list. The append() method adds an item to an existing list. The method returns None, not a copy of an existing list.

Now you’re ready to solve this common Python problem like a professional!

The Python

append()

is a

list

method that can add a new element object at the end of the list. But if we use a

append()

method on a None Type object, we will encounter the

AttributeError: 'NoneType' object has no attribute 'append'

.

In this Python guide, we will explore this error and learn why it occurs in a Python program and solve it. To understand the error better, we will discuss a common example scenario when most python learners encounter this error.

Let’s get started with the Error Statement.

The Error statement

AttributeError: 'NoneType' object has no attribute 'append'

has two parts

  1. Exception Type (

    AttributeError

    )
  2. Error Message (

    'NoneType' object has no attribute 'append'

    )


1. Exception Type (

AttributeError

)

AttributeError is one of the standard Python exceptions. It occurs in a python program when we try to access an unsupported attribute (property or method) using an object. For example, the

append()

method is exclusive to Python lists, but if we try to apply it on a tuple object, we will also receive the AttributeError. Because tuple objects do not have the

append()

method.

tuple_ = (1,2,3,4,5)
tuple_.append(6)  #error

AttributeError: 'tuple' object has no attribute 'append'

 


2. Error Message (

'NoneType' object has no attribute 'append'

)

The error message »

'NoneType' object has no attribute 'append'

» is telling us that we are using the

append()

method on a

NoneType object

. This means we are calling the append method on a variable whose value is

None

.


Example

# A None value object
a = None

# calling append() method on the None value
a.append(2)

print(a)


Output

Traceback (most recent call last):
File "main.py", line 5, in <module>
a.append(2)
AttributeError: 'NoneType' object has no attribute 'append'


Break the code

In the above example, we are getting the error at line 5 with the

a.append(2)

statement. As the value of

a

is

None

and None value does not have any

append()

method, that’s why we are receiving this error.


Common Example Scenario

The most common scenario when many Python programmers commit this error is when they assign the return value of the

append()

method to a Python list variable name and try to call again the

append()

method on the same object. The Python append() method can only append a new value at the end of the list object, and it does not return any value, which means it returns

None

.


For Example

# list object
my_list = [1,2,3,4,5]

# return value of append method 
return_value = my_list.append(6)

print(return_value)


Output

None

From the output, you can see that we get

None

value when we try to assign the return value of

append()

method to a variable.

Many new Python learners do not know about the

None

return value of the

append()

method. They assign the append() method calling statement to the list object, which makes the list object value to

None

. And when they again try to append a new value to the list, they encounter the

AttributeError: 'NoneType' object has no attribute 'append'

Error.


For Example

Let’s write a Python program for to-do tasks. The program will ask the user to enter the 5 tasks that he/she wants to perform. And we will store all those tasks using a list object

todos

. And to add the tasks entered by the user, we will use the list

append()

method.

# create a empty list
todos = []

for i in range(1,6):
    task = input(f"Todo {i}: ")

    # add the task to the todo list
    todos =  todos.append(task)

print("****Your's Today Tasks******")
for i in todos:
    print(i)


Output

Todo 1: workout
Todo 2: clean the house
Traceback (most recent call last):
File "main.py", line 8, in <module>
todos = todos.append(task)
AttributeError: 'NoneType' object has no attribute 'append'


Break the code

In the above example, we are getting the error in line 8 with the statement

todos = todos.append(task)

. The error occurs during the second iteration of the for a loop when we pass the

Todo 2: clean the house

value as an input.

In the first iteration, when we pass the

Todo 1: workout

value, the

todos = todos.append(task)

statement set the value of

todos

to

None

, because the value returned by the

todos.append(task)

statement is None.

That’s why in the second iteration, when the Python tries to call the

append()

method on the

None

object it threw the

AttributeError: 'NoneType' object has no attribute 'append'

error.


Solution

The solution to the above problem is very simple. When we use the append() method on a Python list, we do not need to assign the return value to any object. The simple call of the append() method on a list object will add the new element to the end of the list.

To solve the above example, we only need ensure that we are not assigning the

append()

method return value our

todos

list.


Example Solution

# create a empty list
todos = []

for i in range(1,6):
    task = input(f"Todo {i}: ")

    # add the task to the todo list
    todos.append(task)

print("****Your's Today Tasks******")
for i in todos:
    print(i)


Output

Todo 1: workout
Todo 2: clean the house
Todo 3: have a shower
Todo 4: make the breakfast
Todo 5: start coding
****Your's Today Tasks******
workout
clean the house
have a shower
make the breakfast
start coding


Final Thoughts!

In this Python tutorial, we discussed one of the most Python common errors

AttributeError: 'NoneType' object has no attribute 'append'

. This error occurs in Python when you try to call the append() method on a

None

value. To resolve this error, you need to make sure that you are not assigning any None or returning value of the append() method to your list object.

If you are still getting this error in your Python program, you can share your code in the Comment section. We will try to help you in debugging.


People are also reading:

  • Online Python Compiler

  • Read File in Python

  • Best Python Interpreters

  • Python SyntaxError: can’t assign to function call Solution

  • Python Multiple Inheritance

  • Python typeerror: list indices must be integers or slices, not str Solution

  • Class and Objects in Python

  • Python SyntaxError: unexpected EOF while parsing Solution

  • How to become a Python Developer?

  • How to Play sounds in Python?

NoneType Object Has No Attribute Append in Python

We will learn, with this explanation, about the NoneType error and see what reasons can be to get this error. We will also learn how to fix this error in Python.

Fix the AttributeError: NoneType Object Has No Attribute Append Error in Python

Let’s start by creating a list called product_list and adding a few items inside this list, then append one more item. If we check the items, it works properly, but if we assign None to the product_list and then try to append an item inside this list, it throws a NoneType error.

>>> product_list=['x1','x2']
>>> product_list.append('x3')
>>> product_list
['x1', 'x2', 'x3']
>>> product_list=None
>>> product_list.append('x4')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'append'

This is because the product_list is NoneType, so we can not access this object to append the item, and we can check this object type using the following command.

>>> type(product_list)
<class 'NoneType'>

There can be many reasons for getting this error. One of them is when you try to append an item inside the list and store it to that list variable in which you are appending a new item.

So that the next time you try to append a new item, it throws an error that would be a Nonetype error.

>>> product_list=product_list.append('x3')
>>> product_list.append('x4')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'append'

An attribute can be different not only append, but we can also get this error by accessing another object. If we are getting this error (‘NoneType’ object has no attribute ‘xyz’), the xyz attribute does not exist in an object.

We can check using dir() whether the object we are trying to access exists or not. The append() attribute does not exist inside this list.

>>> dir(product_list)
['__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

For any reason, in Python, you get an AttributeError; you can double-check the official documentation to ensure that what you are trying to do is something that exists. Sometimes when writing a Python script, that could be against Python rules; that is why we get this kind of error.

Python throws error ‘nonetype’ object has no attribute ‘append’ when we try to store the outcome of append in the array. Let’s understand this with an example –

superHeroArray = []
superHeroArray = superHeroArray.append('Captain America')

This code will throw error because append updates the original array. Just like insert, remove, sort etc. it modifies the array and return the default in Python which is None.

The correct way of using append and our code example is –

superHeroArray = []
superHeroArray.append('Captain America')

There is no need to store the result of append to input array because append will return None and superHeroArray will loose the array reference and store None in it.

You can do that same thing without using append function. Check this code –

superHeroArray = []
superHeroArray[len(superHeroArray):] = ['Captain America']

    Tweet this to help others

According to Python documentation, these functions do not return anything –

  • list.append(x)
  • list.insert(i,x)
  • list.remove(x)
  • list.clear()
  • list.reverse()
  • list.sort()

Live Demo

Open Live Demo

This is Akash Mittal, an overall computer scientist. He is in software development from more than 10 years and worked on technologies like ReactJS, React Native, Php, JS, Golang, Java, Android etc. Being a die hard animal lover is the only trait, he is proud of.

Related Tags
  • Error,
  • python error,
  • python-short

Python выводит трассировку (далее traceback), когда в вашем коде появляется ошибка. Вывод traceback может быть немного пугающим, если вы видите его впервые, или не понимаете, чего от вас хотят. Однако traceback Python содержит много информации, которая может помочь вам определить и исправить причину, из-за которой в вашем коде возникла ошибка.

Содержание статьи

  • Traceback — Что это такое и почему оно появляется?
  • Как правильно читать трассировку?
  • Обзор трассировка Python
  • Подробный обзор трассировки в Python
  • Обзор основных Traceback исключений в Python
  • AttributeError
  • ImportError
  • IndexError
  • KeyError
  • NameError
  • SyntaxError
  • TypeError
  • ValueError
  • Логирование ошибок из Traceback
  • Вывод

Понимание того, какую информацию предоставляет traceback Python является основополагающим критерием того, как стать лучшим Python программистом.

К концу данной статьи вы сможете:

  • Понимать, что несет за собой traceback
  • Различать основные виды traceback
  • Успешно вести журнал traceback, при этом исправить ошибку

Python Traceback — Как правильно читать трассировку?

Traceback (трассировка) — это отчет, который содержит вызовы выполненных функций в вашем коде в определенный момент.

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Паблик VK

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

Traceback называют по разному, иногда они упоминаются как трассировка стэка, обратная трассировка, и так далее. В Python используется определение “трассировка”.

Когда ваша программа выдает ошибку, Python выводит текущую трассировку, чтобы подсказать вам, что именно пошло не так. Ниже вы увидите пример, демонстрирующий данную ситуацию:

def say_hello(man):

    print(‘Привет, ‘ + wrong_variable)

say_hello(‘Иван’)

Здесь say_hello() вызывается с параметром man. Однако, в say_hello() это имя переменной не используется. Это связано с тем, что оно написано по другому: wrong_variable в вызове print().

Обратите внимание: в данной статье подразумевается, что вы уже имеете представление об ошибках Python. Если это вам не знакомо, или вы хотите освежить память, можете ознакомиться с нашей статьей: Обработка ошибок в Python

Когда вы запускаете эту программу, вы получите следующую трассировку:

Traceback (most recent call last):

  File «/home/test.py», line 4, in <module>

    say_hello(‘Иван’)

  File «/home/test.py», line 2, in say_hello

    print(‘Привет, ‘ + wrong_variable)

NameError: name ‘wrong_variable’ is not defined

Process finished with exit code 1

Эта выдача из traceback содержит массу информации, которая вам понадобится для определения проблемы. Последняя строка трассировки говорит нам, какой тип ошибки возник, а также дополнительная релевантная информация об ошибке. Предыдущие строки из traceback указывают на код, из-за которого возникла ошибка.

В traceback выше, ошибкой является NameError, она означает, что есть отсылка к какому-то имени (переменной, функции, класса), которое не было определено. В данном случае, ссылаются на имя wrong_variable.

Последняя строка содержит достаточно информации для того, чтобы вы могли решить эту проблему. Поиск переменной wrong_variable, и заменит её атрибутом из функции на man. Однако, скорее всего в реальном случае вы будете иметь дело с более сложным кодом.

Python Traceback — Как правильно понять в чем ошибка?

Трассировка Python содержит массу полезной информации, когда вам нужно определить причину ошибки, возникшей в вашем коде. В данном разделе, мы рассмотрим различные виды traceback, чтобы понять ключевые отличия информации, содержащейся в traceback.

Существует несколько секций для каждой трассировки Python, которые являются крайне важными. Диаграмма ниже описывает несколько частей:

Обзор трассировки Python

В Python лучше всего читать трассировку снизу вверх.

  1. Синее поле: последняя строка из traceback — это строка уведомления об ошибке. Синий фрагмент содержит название возникшей ошибки.
  2. Зеленое поле: после названия ошибки идет описание ошибки. Это описание обычно содержит полезную информацию для понимания причины возникновения ошибки.
  3. Желтое поле: чуть выше в трассировке содержатся различные вызовы функций. Снизу вверх — от самых последних, до самых первых. Эти вызовы представлены двухстрочными вводами для каждого вызова. Первая строка каждого вызова содержит такую информацию, как название файла, номер строки и название модуля. Все они указывают на то, где может быть найден код.
  4. Красное подчеркивание: вторая строка этих вызовов содержит непосредственный код, который был выполнен с ошибкой.

Есть ряд отличий между выдачей трассировок, когда вы запускает код в командной строке, и между запуском кода в REPL. Ниже вы можете видеть тот же код из предыдущего раздела, запущенного в REPL и итоговой выдачей трассировки:

Python 3.7.4 (default, Jul 16 2019, 07:12:58)

[GCC 9.1.0] on linux

Type «help», «copyright», «credits» or «license» for more information.

>>>

>>>

>>> def say_hello(man):

...     print(‘Привет, ‘ + wrong_variable)

...

>>> say_hello(‘Иван’)

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

  File «<stdin>», line 2, in say_hello

NameError: name ‘wrong_variable’ is not defined

Обратите внимание на то, что на месте названия файла вы увидите <stdin>. Это логично, так как вы выполнили код через стандартный ввод. Кроме этого, выполненные строки кода не отображаются в traceback.

Важно помнить: если вы привыкли видеть трассировки стэка в других языках программирования, то вы обратите внимание на явное различие с тем, как выглядит traceback в Python. Большая часть других языков программирования выводят ошибку в начале, и затем ведут сверху вниз, от недавних к последним вызовам.

Это уже обсуждалось, но все же: трассировки Python читаются снизу вверх. Это очень помогает, так как трассировка выводится в вашем терминале (или любым другим способом, которым вы читаете трассировку) и заканчивается в конце выдачи, что помогает последовательно структурировать прочтение из traceback и понять в чем ошибка.

Traceback в Python на примерах кода

Изучение отдельно взятой трассировки поможет вам лучше понять и увидеть, какая информация в ней вам дана и как её применить.

Код ниже используется в примерах для иллюстрации информации, данной в трассировке Python:

Мы запустили ниже предоставленный код в качестве примера и покажем какую информацию мы получили от трассировки.

Сохраняем данный код в файле greetings.py

def who_to_greet(person):

    return person if person else input(‘Кого приветствовать? ‘)

def greet(someone, greeting=‘Здравствуйте’):

    print(greeting + ‘, ‘ + who_to_greet(someone))

def greet_many(people):

    for person in people:

        try:

            greet(person)

        except Exception:

            print(‘Привет, ‘ + person)

Функция who_to_greet() принимает значение person и либо возвращает данное значение если оно не пустое, либо запрашивает  значение от пользовательского ввода через input().

Далее, greet() берет имя для приветствия из someone, необязательное значение из greeting и вызывает print(). Также с переданным значением из someone вызывается who_to_greet().

Наконец, greet_many() выполнит итерацию по списку людей и вызовет greet(). Если при вызове greet() возникает ошибка, то выводится резервное приветствие print('hi, ' + person).

Этот код написан правильно, так что никаких ошибок быть не может при наличии правильного ввода.

Если вы добавите вызов функции greet() в конце нашего кода (которого сохранили в файл greetings.py) и дадите аргумент который он не ожидает (например, greet('Chad', greting='Хай')), то вы получите следующую трассировку:

$ python greetings.py

Traceback (most recent call last):

  File «/home/greetings.py», line 19, in <module>

    greet(‘Chad’, greting=‘Yo’)

TypeError: greet() got an unexpected keyword argument ‘greting’

Еще раз, в случае с трассировкой Python, лучше анализировать снизу вверх. Начиная с последней строки трассировки, вы увидите, что ошибкой является TypeError. Сообщения, которые следуют за типом ошибки, дают вам полезную информацию. Трассировка сообщает, что greet() вызван с аргументом, который не ожидался. Неизвестное название аргумента предоставляется в том числе, в нашем случае это greting.

Поднимаясь выше, вы можете видеть строку, которая привела к исключению. В данном случае, это вызов greet(), который мы добавили в конце greetings.py.

Следующая строка дает нам путь к файлу, в котором лежит код, номер строки этого файла, где вы можете найти код, и то, какой в нем модуль. В нашем случае, так как наш код не содержит никаких модулей Python, мы увидим только надпись , означающую, что этот файл является выполняемым.

С другим файлом и другим вводом, вы можете увидеть, что трассировка явно указывает вам на правильное направление, чтобы найти проблему. Следуя этой информации, мы удаляем злополучный вызов greet() в конце greetings.py, и добавляем следующий файл под названием example.py в папку:

from greetings import greet

greet(1)

Здесь вы настраиваете еще один файл Python, который импортирует ваш предыдущий модуль greetings.py, и используете его greet(). Вот что произойдете, если вы запустите example.py:

$ python example.py

Traceback (most recent call last):

  File «/path/to/example.py», line 3, in <module>

    greet(1)

  File «/path/to/greetings.py», line 5, in greet

    print(greeting + ‘, ‘ + who_to_greet(someone))

TypeError: must be str, not int

В данном случае снова возникает ошибка TypeError, но на этот раз уведомление об ошибки не очень помогает. Оно говорит о том, что где-то в коде ожидается работа со строкой, но было дано целое число.

Идя выше, вы увидите строку кода, которая выполняется. Затем файл и номер строки кода. На этот раз мы получаем имя функции, которая была выполнена — greet().

Поднимаясь к следующей выполняемой строке кода, мы видим наш проблемный вызов greet(), передающий целое число.

Иногда, после появления ошибки, другой кусок кода берет эту ошибку и также её выдает. В таких случаях, Python выдает все трассировки ошибки в том порядке, в котором они были получены, и все по тому же принципу, заканчивая на самой последней трассировке.

Так как это может сбивать с толку, рассмотрим пример. Добавим вызов greet_many() в конце greetings.py:

# greetings.py

...

greet_many([‘Chad’, ‘Dan’, 1])

Это должно привести к выводу приветствия всем трем людям. Однако, если вы запустите этот код, вы увидите несколько трассировок в выдаче:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

$ python greetings.py

Hello, Chad

Hello, Dan

Traceback (most recent call last):

  File «greetings.py», line 10, in greet_many

    greet(person)

  File «greetings.py», line 5, in greet

    print(greeting + ‘, ‘ + who_to_greet(someone))

TypeError: must be str, not int

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File «greetings.py», line 14, in <module>

    greet_many([‘Chad’, ‘Dan’, 1])

  File «greetings.py», line 12, in greet_many

    print(‘hi, ‘ + person)

TypeError: must be str, not int

Обратите внимание на выделенную строку, начинающуюся с “During handling in the output above”. Между всеми трассировками, вы ее увидите.

Это достаточно ясное уведомление: Пока ваш код пытался обработать предыдущую ошибку, возникла новая.

Обратите внимание: функция отображения предыдущих трассировок была добавлена в Python 3. В Python 2 вы можете получать только трассировку последней ошибки.

Вы могли видеть предыдущую ошибку, когда вызывали greet() с целым числом. Так как мы добавили 1 в список людей для приветствия, мы можем ожидать тот же результат. Однако, функция greet_many() оборачивает вызов greet() и пытается в блоке try и except. На случай, если greet() приведет к ошибке, greet_many() захочет вывести приветствие по-умолчанию.

Соответствующая часть greetings.py повторяется здесь:

def greet_many(people):

    for person in people:

        try:

            greet(person)

        except Exception:

            print(‘hi, ‘ + person)

Когда greet() приводит к TypeError из-за неправильного ввода числа, greet_many() обрабатывает эту ошибку и пытается вывести простое приветствие. Здесь код приводит к другой, аналогичной ошибке. Он все еще пытается добавить строку и целое число.

Просмотр всей трассировки может помочь вам увидеть, что стало причиной ошибки. Иногда, когда вы получаете последнюю ошибку с последующей трассировкой, вы можете не увидеть, что пошло не так. В этих случаях, изучение предыдущих ошибок даст лучшее представление о корне проблемы.

Обзор основных Traceback исключений в Python 3

Понимание того, как читаются трассировки Python, когда ваша программа выдает ошибку, может быть очень полезным навыком, однако умение различать отдельные трассировки может заметно ускорить вашу работу.

Рассмотрим основные ошибки, с которыми вы можете сталкиваться, причины их появления и что они значат, а также информацию, которую вы можете найти в их трассировках.

Ошибка AttributeError object has no attribute [Решено]

AttributeError возникает тогда, когда вы пытаетесь получить доступ к атрибуту объекта, который не содержит определенного атрибута. Документация Python определяет, когда эта ошибка возникнет:

Возникает при вызове несуществующего атрибута или присвоение значения несуществующему атрибуту.

Пример ошибки AttributeError:

>>> an_int = 1

>>> an_int.an_attribute

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

AttributeError: ‘int’ object has no attribute ‘an_attribute’

Строка уведомления об ошибке для AttributeError говорит вам, что определенный тип объекта, в данном случае int, не имеет доступа к атрибуту, в нашем случае an_attribute. Увидев AttributeError в строке уведомления об ошибке, вы можете быстро определить, к какому атрибуту вы пытались получить доступ, и куда перейти, чтобы это исправить.

Большую часть времени, получение этой ошибки определяет, что вы возможно работаете с объектом, тип которого не является ожидаемым:

>>> a_list = (1, 2)

>>> a_list.append(3)

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

AttributeError: ‘tuple’ object has no attribute ‘append’

В примере выше, вы можете ожидать, что a_list будет типом списка, который содержит метод .append(). Когда вы получаете ошибку AttributeError, и видите, что она возникла при попытке вызова .append(), это говорит о том, что вы, возможно, не работаете с типом объекта, который ожидаете.

Часто это происходит тогда, когда вы ожидаете, что объект вернется из вызова функции или метода и будет принадлежать к определенному типу, но вы получаете тип объекта None. В данном случае, строка уведомления об ошибке будет выглядеть так:

AttributeError: ‘NoneType’ object has no attribute ‘append’

Python Ошибка ImportError: No module named [Решено]

ImportError возникает, когда что-то идет не так с оператором import. Вы получите эту ошибку, или ее подкласс ModuleNotFoundError, если модуль, который вы хотите импортировать, не может быть найден, или если вы пытаетесь импортировать что-то, чего не существует во взятом модуле. Документация Python определяет, когда возникает эта ошибка:

Ошибка появляется, когда в операторе импорта возникают проблемы при попытке загрузить модуль. Также вызывается, при конструкции импорта from list в from ... import имеет имя, которое невозможно найти.

Вот пример появления ImportError и ModuleNotFoundError:

>>> import asdf

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

ModuleNotFoundError: No module named ‘asdf’

>>> from collections import asdf

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

ImportError: cannot import name ‘asdf’

В примере выше, вы можете видеть, что попытка импорта модуля asdf, который не существует, приводит к ModuleNotFoundError. При попытке импорта того, что не существует (в нашем случае — asdf) из модуля, который существует (в нашем случае — collections), приводит к ImportError. Строки сообщения об ошибке трассировок указывают на то, какая вещь не может быть импортирована, в обоих случаях это asdf.

Ошибка IndexError: list index out of range [Решено]

IndexError возникает тогда, когда вы пытаетесь вернуть индекс из последовательности, такой как список или кортеж, и при этом индекс не может быть найден в последовательности. Документация Python определяет, где эта ошибка появляется:

Возникает, когда индекс последовательности находится вне диапазона.

Вот пример, который приводит к IndexError:

>>> a_list = [‘a’, ‘b’]

>>> a_list[3]

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

IndexError: list index out of range

Строка сообщения об ошибке для IndexError не дает вам полную информацию. Вы можете видеть, что у вас есть отсылка к последовательности, которая не доступна и то, какой тип последовательности рассматривается, в данном случае это список.

Иными словами, в списке a_list нет значения с ключом 3. Есть только значение с ключами 0 и 1, это a и b соответственно.

Эта информация, в сочетании с остальной трассировкой, обычно является исчерпывающей для помощи программисту в быстром решении проблемы.

Возникает ошибка KeyError в Python 3 [Решено]

Как и в случае с IndexError, KeyError возникает, когда вы пытаетесь получить доступ к ключу, который отсутствует в отображении, как правило, это dict. Вы можете рассматривать его как IndexError, но для словарей. Из документации:

Возникает, когда ключ словаря не найден в наборе существующих ключей.

Вот пример появления ошибки KeyError:

>>> a_dict = [‘a’: 1, ‘w’: ‘2’]

>>> a_dict[‘b’]

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

KeyError: ‘b’

Строка уведомления об ошибки KeyError говорит о ключе, который не может быть найден. Этого не то чтобы достаточно, но, если взять остальную часть трассировки, то у вас будет достаточно информации для решения проблемы.

Ошибка NameError: name is not defined в Python [Решено]

NameError возникает, когда вы ссылаетесь на название переменной, модуля, класса, функции, и прочего, которое не определено в вашем коде.

Документация Python дает понять, когда возникает эта ошибка NameError:

Возникает, когда локальное или глобальное название не было найдено.

В коде ниже, greet() берет параметр person. Но в самой функции, этот параметр был назван с ошибкой, persn:

>>> def greet(person):

...     print(f‘Hello, {persn}’)

>>> greet(‘World’)

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

  File «<stdin>», line 2, in greet

NameError: name ‘persn’ is not defined

Строка уведомления об ошибке трассировки NameError указывает вам на название, которое мы ищем. В примере выше, это названная с ошибкой переменная или параметр функции, которые были ей переданы.

NameError также возникнет, если берется параметр, который мы назвали неправильно:

>>> def greet(persn):

...     print(f‘Hello, {person}’)

>>> greet(‘World’)

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

  File «<stdin>», line 2, in greet

NameError: name ‘person’ is not defined

Здесь все выглядит так, будто вы сделали все правильно. Последняя строка, которая была выполнена, и на которую ссылается трассировка выглядит хорошо.

Если вы окажетесь в такой ситуации, то стоит пройтись по коду и найти, где переменная person была использована и определена. Так вы быстро увидите, что название параметра введено с ошибкой.

Ошибка SyntaxError: invalid syntax в Python [Решено]

Возникает, когда синтаксический анализатор обнаруживает синтаксическую ошибку.

Ниже, проблема заключается в отсутствии двоеточия, которое должно находиться в конце строки определения функции. В REPL Python, эта ошибка синтаксиса возникает сразу после нажатия Enter:

>>> def greet(person)

  File «<stdin>», line 1

    def greet(person)

                    ^

SyntaxError: invalid syntax

Строка уведомления об ошибке SyntaxError говорит вам только, что есть проблема с синтаксисом вашего кода. Просмотр строк выше укажет вам на строку с проблемой. Каретка ^ обычно указывает на проблемное место. В нашем случае, это отсутствие двоеточия в операторе def нашей функции.

Стоит отметить, что в случае с трассировками SyntaxError, привычная первая строка Tracebak (самый последний вызов) отсутствует. Это происходит из-за того, что SyntaxError возникает, когда Python пытается парсить ваш код, но строки фактически не выполняются.

Ошибка TypeError в Python 3 [Решено]

TypeError возникает, когда ваш код пытается сделать что-либо с объектом, который не может этого выполнить, например, попытка добавить строку в целое число, или вызвать len() для объекта, в котором не определена длина.

Ошибка возникает, когда операция или функция применяется к объекту неподходящего типа.

Рассмотрим несколько примеров того, когда возникает TypeError:

>>> 1 + ‘1’

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

>>> ‘1’ + 1

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

TypeError: must be str, not int

>>> len(1)

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

TypeError: object of type ‘int’ has no len()

Указанные выше примеры возникновения TypeError приводят к строке уведомления об ошибке с разными сообщениями. Каждое из них весьма точно информирует вас о том, что пошло не так.

В первых двух примерах мы пытаемся внести строки и целые числа вместе. Однако, они немного отличаются:

  • В первом примере мы пытаемся добавить str к int.
  • Во втором примере мы пытаемся добавить int к str.

Уведомления об ошибке указывают на эти различия.

Последний пример пытается вызвать len() для int. Сообщение об ошибке говорит нам, что мы не можем сделать это с int.

Возникла ошибка ValueError в Python 3 [Решено]

ValueError возникает тогда, когда значение объекта не является корректным. Мы можем рассматривать это как IndexError, которая возникает из-за того, что значение индекса находится вне рамок последовательности, только ValueError является более обобщенным случаем.

Возникает, когда операция или функция получает аргумент, который имеет правильный тип, но неправильное значение, и ситуация не описывается более детальной ошибкой, такой как IndexError.

Вот два примера возникновения ошибки ValueError:

>>> a, b, c = [1, 2]

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

ValueError: not enough values to unpack (expected 3, got 2)

>>> a, b = [1, 2, 3]

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

ValueError: too many values to unpack (expected 2)

Строка уведомления об ошибке ValueError в данных примерах говорит нам в точности, в чем заключается проблема со значениями:

  1. В первом примере, мы пытаемся распаковать слишком много значений. Строка уведомления об ошибке даже говорит нам, где именно ожидается распаковка трех значений, но получаются только два.
  2. Во втором примере, проблема в том, что мы получаем слишком много значений, при этом получаем недостаточно значений для распаковки.

Логирование ошибок из Traceback в Python 3

Получение ошибки, и ее итоговой трассировки указывает на то, что вам нужно предпринять для решения проблемы. Обычно, отладка кода — это первый шаг, но иногда проблема заключается в неожиданном, или некорректном вводе. Хотя важно предусматривать такие ситуации, иногда есть смысл скрывать или игнорировать ошибку путем логирования traceback.

Рассмотрим жизненный пример кода, в котором нужно заглушить трассировки Python. В этом примере используется библиотека requests.

Файл urlcaller.py:

import sys

import requests

response = requests.get(sys.argv[1])

print(response.status_code, response.content)

Этот код работает исправно. Когда вы запускаете этот скрипт, задавая ему URL в качестве аргумента командной строки, он откроет данный URL, и затем выведет HTTP статус кода и содержимое страницы (content) из response. Это работает даже в случае, если ответом является статус ошибки HTTP:

$ python urlcaller.py https://httpbin.org/status/200

200 b»

$ python urlcaller.py https://httpbin.org/status/500

500 b»

Однако, иногда данный URL не существует (ошибка 404 — страница не найдена), или сервер не работает. В таких случаях, этот скрипт приводит к ошибке ConnectionError и выводит трассировку:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

$ python urlcaller.py http://thisurlprobablydoesntexist.com

...

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File «urlcaller.py», line 5, in <module>

    response = requests.get(sys.argv[1])

  File «/path/to/requests/api.py», line 75, in get

    return request(‘get’, url, params=params, **kwargs)

  File «/path/to/requests/api.py», line 60, in request

    return session.request(method=method, url=url, **kwargs)

  File «/path/to/requests/sessions.py», line 533, in request

    resp = self.send(prep, **send_kwargs)

  File «/path/to/requests/sessions.py», line 646, in send

    r = adapter.send(request, **kwargs)

  File «/path/to/requests/adapters.py», line 516, in send

    raise ConnectionError(e, request=request)

requests.exceptions.ConnectionError: HTTPConnectionPool(host=‘thisurlprobablydoesntexist.com’, port=80): Max retries exceeded with url: / (Caused by NewConnectionError(‘<urllib3.connection.HTTPConnection object at 0x7faf9d671860>: Failed to establish a new connection: [Errno -2] Name or service not known’,))

Трассировка Python в данном случае может быть очень длинной, и включать в себя множество других ошибок, которые в итоге приводят к ошибке ConnectionError. Если вы перейдете к трассировке последних ошибок, вы заметите, что все проблемы в коде начались на пятой строке файла urlcaller.py.

Если вы обернёте неправильную строку в блоке try и except, вы сможете найти нужную ошибку, которая позволит вашему скрипту работать с большим числом вводов:

Файл urlcaller.py:

try:

    response = requests.get(sys.argv[1])

except requests.exceptions.ConnectionError:

    print(1, ‘Connection Error’)

else:

    print(response.status_code, response.content)

Код выше использует предложение else с блоком except.

Теперь, когда вы запускаете скрипт на URL, который приводит к ошибке ConnectionError, вы получите -1 в статусе кода и содержимое ошибки подключения:

$ python urlcaller.py http://thisurlprobablydoesntexist.com

1 Connection Error

Это работает отлично. Однако, в более реалистичных системах, вам не захочется просто игнорировать ошибку и итоговую трассировку, вам скорее понадобиться внести в журнал. Ведение журнала трассировок позволит вам лучше понять, что идет не так в ваших программах.

Обратите внимание: Для более лучшего представления о системе логирования в Python вы можете ознакомиться с данным руководством тут: Логирование в Python

Вы можете вести журнал трассировки в скрипте, импортировав пакет logging, получить logger, вызвать .exception() для этого логгера в куске except блока try и except. Конечный скрипт будет выглядеть примерно так:

# urlcaller.py

import logging

import sys

import requests

logger = logging.getLogger(__name__)

try:

    response = requests.get(sys.argv[1])

except requests.exceptions.ConnectionError as e:

    logger.exception()

    print(1, ‘Connection Error’)

else:

    print(response.status_code, response.content)

Теперь, когда вы запускаете скрипт с проблемным URL, он будет выводить исключенные -1 и ConnectionError, но также будет вести журнал трассировки:

$ python urlcaller.py http://thisurlprobablydoesntexist.com

...

  File «/path/to/requests/adapters.py», line 516, in send

    raise ConnectionError(e, request=request)

requests.exceptions.ConnectionError: HTTPConnectionPool(host=‘thisurlprobablydoesntexist.com’, port=80): Max retries exceeded with url: / (Caused by NewConnectionError(‘<urllib3.connection.HTTPConnection object at 0x7faf9d671860>: Failed to establish a new connection: [Errno -2] Name or service not known’,))

1 Connection Error

По умолчанию, Python будет выводить ошибки в стандартный stderr. Выглядит так, будто мы совсем не подавили вывод трассировки. Однако, если вы выполните еще один вызов при перенаправлении stderr, вы увидите, что система ведения журналов работает, и мы можем изучать логи программы без необходимости личного присутствия во время появления ошибок:

$ python urlcaller.py http://thisurlprobablydoesntexist.com 2> mylogs.log

1 Connection Error

Подведем итоги данного обучающего материала

Трассировка Python содержит замечательную информацию, которая может помочь вам понять, что идет не так с вашим кодом Python. Эти трассировки могут выглядеть немного запутанно, но как только вы поймете что к чему, и увидите, что они в себе несут, они могут быть предельно полезными. Изучив несколько трассировок, строку за строкой, вы получите лучшее представление о предоставляемой информации.

Понимание содержимого трассировки Python, когда вы запускаете ваш код может быть ключом к улучшению вашего кода. Это способ, которым Python пытается вам помочь.

Теперь, когда вы знаете как читать трассировку Python, вы можете выиграть от изучения ряда инструментов и техник для диагностики проблемы, о которой вам сообщает трассировка. Модуль traceback может быть полезным, если вам нужно узнать больше из выдачи трассировки.

  • Текст является переводом статьи: Understanding the Python Traceback
  • Изображение из шапки статьи принадлежит сайту © Real Python

Являюсь администратором нескольких порталов по обучению языков программирования Python, Golang и Kotlin. В составе небольшой команды единомышленников, мы занимаемся популяризацией языков программирования на русскоязычную аудиторию. Большая часть статей была адаптирована нами на русский язык и распространяется бесплатно.

E-mail: vasile.buldumac@ati.utm.md

Образование
Universitatea Tehnică a Moldovei (utm.md)

  • 2014 — 2018 Технический Университет Молдовы, ИТ-Инженер. Тема дипломной работы «Автоматизация покупки и продажи криптовалюты используя технический анализ»
  • 2018 — 2020 Технический Университет Молдовы, Магистр, Магистерская диссертация «Идентификация человека в киберпространстве по фотографии лица»

Errors are an essential part of a programmer’s life. And it is not at all bad if you get an error. Getting error means you are learning something new. But we need to solve those errors. And before solving that error, we should know why we are getting that error. There are some commonly occurred errors in python like Type Error, Syntax Error, Key Error, Attribute error, Name Error, and so on.  

In this article, we will learn about what is python Attribute Error, why we get it, and how we resolve it? Python interpreter raises an Attribute Error when we try to call or access an attribute of an object, but that object does not possess that attribute. For example- If we try using upper() on an integer, we will get an attribute error.  

Why we Get Attribute Error? 

Whenever we try to access an attribute that is not possessed by that object, we get an attribute error. For example- We know that to make the string uppercase, we use the upper(). 

Output- 

AttributeError: 'int' object has no attribute 'upper' 

Here, we are trying to convert an integer to an upper case letter, which is not possible as integers do not attribute being upper or lower. But if try using this upper() on a string, we would have got a result because a string can be qualified as upper or lower.  

Some Common Mistakes which result in Attribute error in python 

If we try to perform append() on any data type other than List: 

Sometimes when we want to concatenate two strings we try appending one string into another, which is not possible and we get an Attribute Error. 

string1="Ashwini" 
string2="Mandani" 
string1.append(string2) 

Output- 

AttributeError: 'str' object has no attribute 'append' 

Same goes with tuples, 

a=tuple((5,6)) 
a.append(7) 

Output- 

AttributeError: 'tuple' object has no attribute 'append' 

Trying to access attribute of Class: 

Sometimes, what we do is that we try to access attributes of a class which it does not possess. Let us better understand it with an example. 

Here, we have two classes- One is Person class and the other is Vehicle class. Both possess different properties. 

class Person: 

   def __init__(self,age,gender,name): 
       self.age=age 
       self.gender=gender 
       self.name=name 

   def speak(self): 
        print("Hello!! How are you?") 

class Vehicle: 

   def __init__(self , model_type , engine_type): 
        self.model_type = model_type 
        self.engine_type = engine_type 

   def horn(self): 
        print("beep!! beep") 

ashwini=Person(20,"male","ashwini") 
print(ashwini.gender) 
print(ashwini.engine_type) 

Output- 

male  
AttributeError: 'Person' object has no attribute 'engine_type'  
AttributeError: 'Person' object has no attribute 'horn' 
car=Vehicle( "Hatchback" , "Petrol" ) 
print(car.engine_type) 
print(car.gender) 

Output- 

Petrol 
AttributeError: 'Vehicle' object has no attribute 'gender' 
Error-
AttributeError: 'Vehicle' object has no attribute 'speak' 

In the above examples, when we tried to access the gender property of Person Class, we were successful. But when we tried to access the engine_type() attribute, it showed us an error. It is because a Person has no attribute called engine_type. Similarly, when we tried calling engine_type on Vehicle, we were successful, but that was not in the case of gender, as Vehicle has no attribute called gender. 

AttributeError: ‘NoneType’

We get NoneType Error when we get ‘None’ instead of the instance we are supposing we will get. It means that an assignment failed or returned an unexpected result.

name=None
i=5
if i%2==0:
    name="ashwini"
name.upper()

Output-

AttributeError: 'NoneType' object has no attribute 'upper'

While working with Modules:

It is very common to encounter an attribute error while working with modules. Suppose, we are importing a module named hello and trying to access two functions in it. One is print_name() and another is print_age().

Module Hello-

def print_name():
    print("Hello! The name of this module is module1")

import hello

hello.print_name()
hello.print_age()

Output-

Hello! The name of this module is module1

AttributeError: module 'hello' has no attribute 'print_age'

As the module hello does not contain print_age attribute, we got an Attribute error. In the next section, we will learn how to resolve this error.

How to Resolve Attribute Error in Python 

Use help():

The developers of python have tried to solve any possible problem faced by Python programmers. In this case, too, if we are getting confused, that whether a particular attribute belongs to an object or not, we can make use of help(). For example, if we don’t know whether we can use append() on a string, we can print(help(str)) to know all the operations that we can perform on strings. Not only these built-in data types, but we can also use help() on user-defined data types like Class.  

For example- if we don’t know what attributes does class Person that we declared above has,  

print(help(Person)) 

Output- 

python attribute error

Isn’t it great! These are precisely the attributes we defined in our Person class. 

Now, let us try using help() on our hello module inside the hi module.

Help on module hello:
NAME
hello
FUNCTIONS
print_name()

Using Try – Except Statement 

A very professional way to tackle not only Attribute error but any error is by using try-except statements. If we think we might get an error in a particular block of code, we can enclose them in a try block. Let us see how to do this. 

Suppose, we are not sure whether Person class contain engine_type attribute or not, we can enclose it in try block. 

class Vehicle: 

   def __init__(self , model_type , engine_type): 
        self.model_type = model_type 
        self.engine_type = engine_type 

   def horn(self): 
        print("beep!! beep") 

car=Vehicle( "Hatchback" , "Petrol" ) 

try: 
   print(car.engine_type) 
   print(car.gender) 

except Exception as e: 
   print(e)  

Output- 

Petrol 
'Vehicle' object has no attribute 'gender'. 

Must Read

  • How to Convert String to Lowercase in
  • How to Calculate Square Root
  • User Input | Input () Function | Keyboard Input
  • Best Book to Learn Python

Conclusion 

Whenever to try to access an attribute of an object that does not belong to it, we get an Attribute Error in Python. We can tackle it using either help() function or try-except statements. 

Try to run the programs on your side and let us know if you have any queries.

Happy Coding!

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Npm err a complete log of this run can be found in вылетает ошибка
  • Np 41772 1 ошибка ps4 как исправить на русском