[Solved] TypeError: ‘str’ Object Does Not Support Item Assignment

TypeError:'str' Object Does Not Support Item Assignment

In this article, we will be discussing the TypeError:’str’ Object Does Not Support Item Assignment exception . We will also be going through solutions to this problem with example programs.

Why is This Error Raised?

When you attempt to change a character within a string using the assignment operator, you will receive the Python error TypeError: ‘str’ object does not support item assignment.

As we know, strings are immutable. If you attempt to change the content of a string, you will receive the error TypeError: ‘str’ object does not support item assignment .

There are four other similar variations based on immutable data types :

  • TypeError: 'tuple' object does not support item assignment
  • TypeError: 'int' object does not support item assignment
  • TypeError: 'float' object does not support item assignment
  • TypeError: 'bool' object does not support item assignment

Replacing String Characters using Assignment Operators

Replicate these errors yourself online to get a better idea here .

In this code, we will attempt to replace characters in a string.

str object does not support item assignment

Strings are an immutable data type. However, we can change the memory to a different set of characters like so:

TypeError: ‘str’ Object Does Not Support Item Assignment in JSON

Let’s review the following code, which retrieves data from a JSON file.

In line 5, we are assigning data['sample'] to a string instead of an actual dictionary. This causes the interpreter to believe we are reassigning the value for an immutable string type.

TypeError: ‘str’ Object Does Not Support Item Assignment in PySpark

The following program reads files from a folder in a loop and creates data frames.

This occurs when a PySpark function is overwritten with a string. You can try directly importing the functions like so:

TypeError: ‘str’ Object Does Not Support Item Assignment in PyMongo

The following program writes decoded messages in a MongoDB collection. The decoded message is in a Python Dictionary.

At the 10th visible line, the variable x is converted as a string.

It’s better to use:

Please note that msg are a dictionary and NOT an object of context.

TypeError: ‘str’ Object Does Not Support Item Assignment in Random Shuffle

The below implementation takes an input main and the value is shuffled. The shuffled value is placed into Second .

random.shuffle is being called on a string, which is not supported. Convert the string type into a list and back to a string as an output in Second

TypeError: ‘str’ Object Does Not Support Item Assignment in Pandas Data Frame

The following program attempts to add a new column into the data frame

The iteration statement for dataset in df: loops through all the column names of “sample.csv”. To add an extra column, remove the iteration and simply pass dataset['Column'] = 1 .

[Solved] runtimeerror: cuda error: invalid device ordinal

These are the causes for TypeErrors : – Incompatible operations between 2 operands: – Passing a non-callable identifier – Incorrect list index type – Iterating a non-iterable identifier.

The data types that support item assignment are: – Lists – Dictionaries – and Sets These data types are mutable and support item assignment

As we know, TypeErrors occur due to unsupported operations between operands. To avoid facing such errors, we must: – Learn Proper Python syntax for all Data Types. – Establish the mutable and immutable Data Types. – Figure how list indexing works and other data types that support indexing. – Explore how function calls work in Python and various ways to call a function. – Establish the difference between an iterable and non-iterable identifier. – Learn the properties of Python Data Types.

We have looked at various error cases in TypeError:’str’ Object Does Not Support Item Assignment. Solutions for these cases have been provided. We have also mentioned similar variations of this exception.

Trending Python Articles

[Fixed] typeerror can’t compare datetime.datetime to datetime.date

Fix Python TypeError: 'str' object does not support item assignment

by Nathan Sebhastian

Posted on Jan 11, 2023

Reading time: 4 minutes

python dict 'str' object does not support item assignment

Python shows TypeError: 'str' object does not support item assignment error when you try to access and modify a string object using the square brackets ( [] ) notation.

To solve this error, use the replace() method to modify the string instead.

This error occurs because a string in Python is immutable, meaning you can’t change its value after it has been defined.

For example, suppose you want to replace the first character in your string as follows:

The code above attempts to replace the letter H with J by adding the index operator [0] .

But because assigning a new value to a string is not possible, Python responds with the following error:

To fix this error, you can create a new string with the desired modifications, instead of trying to modify the original string.

This can be done by calling the replace() method from the string. See the example below:

The replace() method allows you to replace all occurrences of a substring in your string.

This method accepts 3 parameters:

  • old - the substring you want to replace
  • new - the replacement for old value
  • count - how many times to replace old (optional)

By default, the replace() method replaces all occurrences of the old string:

You can control how many times the replacement occurs by passing the third count parameter.

The code below replaces only the first occurrence of the old value:

And that’s how you can modify a string using the replace() method.

If you want more control over the modification, you can use a list.

Convert the string to a list first, then access the element you need to change as shown below:

After you modify the list element, merge the list back as a string by using the join() method.

This solution gives you more control as you can select the character you want to replace. You can replace the first, middle, or last occurrence of a specific character.

Another way you can modify a string is to use the string slicing and concatenation method.

Consider the two examples below:

In both examples, the string slicing operator is used to extract substrings of the old_str variable.

In the first example, the slice operator is used to extract the substring starting from index 1 to the end of the string with old_str[1:] and concatenates it with the character ‘J’ .

In the second example, the slice operator is used to extract the substring before index 7 with old_str[:7] and the substring after index 8 with old_str[8:] syntax.

Both substrings are joined together while putting the character x in the middle.

The examples show how you can use slicing to extract substrings and concatenate them to create new strings.

But using slicing and concatenation can be more confusing than using a list, so I would recommend you use a list unless you have a strong reason.

The Python error TypeError: 'str' object does not support item assignment occurs when you try to modify a string object using the subscript or index operator assignment.

This error happens because strings in Python are immutable and can’t be modified.

The solution is to create a new string with the required modifications. There are three ways you can do it:

  • Use replace() method
  • Convert the string to a list, apply the modifications, merge the list back to a string
  • Use string slicing and concatenation to create a new string

Now you’ve learned how to modify a string in Python. Nice work!

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials. Learn statistics, JavaScript and other programming languages using clear examples written for people.

Learn more about this website

Connect with me on Twitter

Or LinkedIn

Type the keyword below and hit enter

Click to see all tutorials tagged with:

python dict 'str' object does not support item assignment

Explore your training options in 10 minutes Get Started

  • Graduate Stories
  • Partner Spotlights
  • Bootcamp Prep
  • Bootcamp Admissions
  • University Bootcamps
  • Coding Tools
  • Software Engineering
  • Web Development
  • Data Science
  • Tech Guides
  • Tech Resources
  • Career Advice
  • Online Learning
  • Internships
  • Apprenticeships
  • Tech Salaries
  • Associate Degree
  • Bachelor's Degree
  • Master's Degree
  • University Admissions
  • Best Schools
  • Certifications
  • Bootcamp Financing
  • Higher Ed Financing
  • Scholarships
  • Financial Aid
  • Best Coding Bootcamps
  • Best Online Bootcamps
  • Best Web Design Bootcamps
  • Best Data Science Bootcamps
  • Best Technology Sales Bootcamps
  • Best Data Analytics Bootcamps
  • Best Cybersecurity Bootcamps
  • Best Digital Marketing Bootcamps
  • Los Angeles
  • San Francisco
  • Browse All Locations
  • Digital Marketing
  • Machine Learning
  • See All Subjects
  • Bootcamps 101
  • Full-Stack Development
  • Career Changes
  • View all Career Discussions
  • Mobile App Development
  • Cybersecurity
  • Product Management
  • UX/UI Design
  • What is a Coding Bootcamp?
  • Are Coding Bootcamps Worth It?
  • How to Choose a Coding Bootcamp
  • Best Online Coding Bootcamps and Courses
  • Best Free Bootcamps and Coding Training
  • Coding Bootcamp vs. Community College
  • Coding Bootcamp vs. Self-Learning
  • Bootcamps vs. Certifications: Compared
  • What Is a Coding Bootcamp Job Guarantee?
  • How to Pay for Coding Bootcamp
  • Ultimate Guide to Coding Bootcamp Loans
  • Best Coding Bootcamp Scholarships and Grants
  • Education Stipends for Coding Bootcamps
  • Get Your Coding Bootcamp Sponsored by Your Employer
  • GI Bill and Coding Bootcamps
  • Tech Intevriews
  • Our Enterprise Solution
  • Connect With Us
  • Publication
  • Reskill America
  • Partner With Us

Career Karma

  • Resource Center
  • Bachelor’s Degree
  • Master’s Degree

Python ‘str’ object does not support item assignment solution

Strings in Python are immutable. This means that they cannot be changed. If you try to change the contents of an existing string, you’re liable to find an error that says something like “‘str’ object does not support item assignment”.

In this guide, we’re going to talk about this common Python error and how it works. We’ll walk through a code snippet with this error present so we can explore how to fix it.

Find your bootcamp match

The problem: ‘str’ object does not support item assignment.

Let’s start by taking a look at our error: Typeerror: ‘str’ object does not support item assignment.

This error message tells us that a string object (a sequence of characters) cannot be assigned an item. This error is raised when you try to change the value of a string using the assignment operator.

The most common scenario in which this error is raised is when you try to change a string by its index values . The following code yields the item assignment error:

You cannot change the character at the index position 0 because strings are immutable.

You should check to see if there are any string methods that you can use to create a modified copy of a string if applicable. You could also use slicing if you want to create a new string based on parts of an old string.

An Example Scenario

We’re going to write a program that checks whether a number is in a string. If a number is in a string, it should be replaced with an empty string. This will remove the number. Our program is below:

This code accepts a username from the user using the input() method . It then loops through every character in the username using a for loop and checks if that character is a number. If it is, we try to replace that character with an empty string. Let’s run our code and see what happens:

Our code has returned an error.

The cause of this error is that we’re trying to assign a string to an index value in “name”:

The Solution

We can solve this error by adding non-numeric characters to a new string. Let’s see how it works:

This code replaces the character at name[c] with an empty string. 

We have created a separate variable called “final_username”. This variable is initially an empty string. If our for loop finds a character that is not a number, that character is added to the end of the “final_username” string. Otherwise, nothing happens. We check to see if a character is a number using the isnumeric() method.

We add a character to the “final_username” string using the addition assignment operator. This operator adds one value to another value. In this case, the operator adds a character to the end of the “final_username” string.

Let’s run our code:

Our code successfully removed all of the numbers from our string. This code works because we are no longer trying to change an existing string. We instead create a new string called “final_username” to which we add all the letter-based characters from our username string.

In Python, strings cannot be modified. You need to create a new string based on the contents of an old one if you want to change a string.

The “‘str’ object does not support item assignment” error tells you that you are trying to modify the value of an existing string.

Now you’re ready to solve this Python error like an expert.

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication .

What's Next?

icon_10

Get matched with top bootcamps

Ask a question to our community, take our careers quiz.

James Gallagher

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Apply to top tech training programs in one click

The Research Scientist Pod

How to Solve Python TypeError: ‘str’ object does not support item assignment

by Suf | Programming , Python , Tips

Strings are immutable objects, which means you cannot change them once created. If you try to change a string in place using the indexing operator [], you will raise the TypeError: ‘str’ object does not support item assignment.

To solve this error, you can use += to add characters to a string.

a += b is the same as a = a + b

Generally, you should check if there are any string methods that can create a modified copy of the string for your needs.

This tutorial will go through how to solve this error and solve it with the help of code examples.

Table of contents

Python typeerror: ‘str’ object does not support item assignment, solution #1: create new string using += operator, solution #2: create new string using str.join() and list comprehension.

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type.

The part 'str' object tells us that the error concerns an illegal operation for strings.

The part does not support item assignment tells us that item assignment is the illegal operation we are attempting.

Strings are immutable objects which means we cannot change them once created. We have to create a new string object and add the elements we want to that new object. Item assignment changes an object in place, which is only suitable for mutable objects like lists. Item assignment is suitable for lists because they are mutable.

Let’s look at an example of assigning items to a list. We will iterate over a list and check if each item is even. If the number is even, we will assign the square of that number in place at that index position.

Let’s run the code to see the result:

We can successfully do item assignment on a list.

Let’s see what happens when we try to change a string using item assignment:

We cannot change the character at position -1 (last character) because strings are immutable. We need to create a modified copy of a string, for example using replace() :

In the above code, we create a copy of the string using = and call the replace function to replace the lower case h with an upper case H .

Let’s look at another example.

In this example, we will write a program that takes a string input from the user, checks if there are vowels in the string, and removes them if present. First, let’s define the vowel remover function.

We check if each character in a provided string is a member of the vowels list in the above code. If the character is a vowel, we attempt to replace that character with an empty string. Next, we will use the input() method to get the input string from the user.

Altogether, the program looks like this:

The error occurs because of the line: string[ch] = "" . We cannot change a string in place because strings are immutable.

We can solve this error by creating a modified copy of the string using the += operator. We have to change the logic of our if statement to the condition not in vowels . Let’s look at the revised code:

Note that in the vowel_remover function, we define a separate variable called new_string , which is initially empty. If the for loop finds a character that is not a vowel, we add that character to the end of the new_string string using += . We check if the character is not a vowel with the if statement: if string[ch] not in vowels .

We successfully removed all vowels from the string.

We can solve this error by creating a modified copy of the string using list comprehension. List comprehension provides a shorter syntax for creating a new list based on the values of an existing list.

Let’s look at the revised code:

In the above code, the list comprehension creates a new list of characters from the string if the characters are not in the list of vowels. We then use the join() method to convert the list to a string. Let’s run the code to get the result:

We successfully removed all vowels from the input string.

Congratulations on reading to the end of this tutorial. The TypeError: ‘str’ object does not support item assignment occurs when you try to change a string in-place using the indexing operator [] . You cannot modify a string once you create it. To solve this error, you need to create a new string based on the contents of the existing string. The common ways to change a string are:

  • List comprehension
  • The String replace() method
  • += Operator

For further reading on TypeErrors, go to the articles:

  • How to Solve Python TypeError: object of type ‘NoneType’ has no len()
  • How to Solve Python TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’
  • How to Solve Python TypeError: ‘tuple’ object does not support item assignment
  • How to Solve Python TypeError: ‘set’ object does not support item assignment

To learn more about Python for data science and machine learning, go to the  online courses page on Python  for the most comprehensive courses available.

Have fun and happy researching!

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Telegram (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Tumblr (Opens in new window)

How to Fix STR Object Does Not Support Item Assignment Error in Python

  • Python How-To's
  • How to Fix STR Object Does Not Support …

How to Fix STR Object Does Not Support Item Assignment Error in Python

In Python, strings are immutable, so we will get the str object does not support item assignment error when trying to change the string.

You can not make some changes in the current value of the string. You can either rewrite it completely or convert it into a list first.

This whole guide is all about solving this error. Let’s dive in.

Fix str object does not support item assignment Error in Python

As the strings are immutable, we can not assign a new value to one of its indexes. Take a look at the following code.

The above code will give o as output, and later it will give an error once a new value is assigned to its fourth index.

The string works as a single value; although it has indexes, you can not change their value separately. However, if we convert this string into a list first, we can update its value.

The above code will run perfectly.

First, we create a list of string elements. As in the list, all elements are identified by their indexes and are mutable.

We can assign a new value to any of the indexes of the list. Later, we can use the join function to convert the same list into a string and store its value into another string.

Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

Related Article - Python Error

  • Can Only Concatenate List (Not Int) to List in Python
  • How to Fix Value Error Need More Than One Value to Unpack in Python
  • How to Fix ValueError Arrays Must All Be the Same Length in Python
  • Invalid Syntax in Python
  • How to Fix the TypeError: Object of Type 'Int64' Is Not JSON Serializable
  • How to Fix the TypeError: 'float' Object Cannot Be Interpreted as an Integer in Python

Codingdeeply

Python String Error: ‘str’ Object Does Not Support Item Assignment

If you have encountered the error message “Python String Error: ‘str’ Object Does Not Support Item Assignment,” then you may have been attempting to modify a string object directly or assigning an item to a string object incorrectly.

This error message indicates that the ‘str’ object type in Python is immutable, meaning that once a string object is created, it cannot be modified.

In this article, we will dive into the details of this error message, explore why it occurs, and provide solutions and best practices to resolve and prevent it.

By the end of this article, you will have a better understanding of how to work with strings in Python and avoid common mistakes that lead to this error.

Table of Contents

Advertising links are marked with *. We receive a small commission on sales, nothing changes for you.

Understanding the error message

Python String Error: 'str' Object Does Not Support Item Assignment

When encountering the Python String Error: ‘str’ Object Does Not Support Item Assignment, it’s essential to understand what the error message means.

This error message typically occurs when one attempts to modify a string directly through an item assignment.

Strings in Python are immutable, meaning that their contents cannot be changed once they have been created. Therefore, when trying to assign an item to a string object, the interpreter throws this error message.

For example, consider the following code snippet:

string = “hello” string[0] = “H”

When executing this code, the interpreter will raise the Python String Error: ‘str’ Object Does Not Support Item Assignment. Since strings are immutable in Python, it’s impossible to change any individual character in the string object through item assignment.

It’s important to note that this error message is solely related to item assignment. Other string manipulations, such as concatenation and slicing, are still possible.

Understanding the ‘str’ object

The ‘str’ object is a built-in data type in Python and stands for string. Strings are a collection of characters enclosed within single or double quotes, and in Python, these strings are immutable.

While it’s impossible to modify an existing string directly, we can always create a new string using string manipulation functions like concatenation, replace, and split, among others.

In fact, these string manipulation functions are specifically designed to work on immutable strings and provide a wide range of flexibility when working with strings.

Common causes of the error

The “Python String Error: ‘str’ Object Does Not Support Item Assignment” error can occur due to various reasons. Here are some of the common causes:

1. Attempting to modify a string directly

Strings are immutable data types, meaning their values cannot be changed after creation.

Therefore, trying to modify a string directly by assigning a new value to a specific index or item will result in the “Python String Error: ‘str’ Object Does Not Support Item Assignment” error.

string = "Hello World" string[0] = "h"

This will result in the following error message:

TypeError: 'str' object does not support item assignment

2. Misunderstanding the immutability of string objects

As mentioned earlier, string objects are immutable, unlike other data types like lists or dictionaries.

Thus, attempting to change the value of a string object after it is created will result in the “Python String Error: ‘str’ Object Does Not Support Item Assignment” error.

string = "Hello World" string += "!" string[0] = "h"

3. Using the wrong data type for assignment

If you are trying to assign a value of the wrong data type to a string, such as a list or tuple, you can encounter the “Python String Error: ‘str’ Object Does Not Support Item Assignment” error.

string = "Hello World" string[0] = ['h']

TypeError: 'list' object does not support item assignment

Ensure that you use the correct data type when assigning values to a string object to avoid this error.

Resolving the error

There are several techniques available to fix the Python string error: ‘str’ Object Does Not Support Item Assignment.

Here are some solutions:

Using string manipulation methods

One way to resolve the error is to use string manipulation functions that do not require item assignment.

For example, to replace a character in a string at a specific index, use the replace() method instead of assigning a new value to the index. Similarly, to delete a character at a particular position, use the slice() method instead of an item assignment.

Creating a new string object

If you need to modify a string, you can create a new string object based on the original.

One way to modify text is by combining the portions before and after the edited section. This can be achieved by concatenating substrings.

Alternatively, you can use string formatting techniques to insert new values into the string.

Converting the string to a mutable data type

Strings are immutable, which means that their contents cannot be changed.

Nevertheless, you can convert a string to a mutable data type such as a list, modify the list, and then convert it back to a string. Be aware that this approach can have performance implications, especially for larger strings.

When implementing any of these solutions, it’s essential to keep in mind the context of your code and consider the readability and maintainability of your solution.

Best practices to avoid the error

To avoid encountering the “Python String Error: ‘str’ Object Does Not Support Item Assignment,” following some best practices when working with string objects is important.

Here are some tips:

1. Understand string immutability

Strings are immutable objects in Python, meaning they cannot be changed once created.

Attempting to modify a string directly will result in an error. Instead, create a new string object or use string manipulation methods.

2. Use appropriate data types

When creating variables, it is important to use the appropriate data type. If you need to modify a string, consider using a mutable data type such as a list or bytearray instead.

3. Utilize string manipulation functions effectively

Python provides many built-in string manipulation functions that can be used to modify strings without encountering this error. Some commonly used functions include:

  • replace() – replaces occurrences of a substring with a new string
  • split() – splits a string into a list of substrings
  • join() – combines a list of strings into a single string
  • format() – formats a string with variables

4. Avoid using index-based assignment

Index-based assignment (e.g. string[0] = ‘a’) is not supported for strings in Python. Instead, you can create a new string with the modified value.

5. Be aware of context

When encountering this error, it is important to consider the context in which it occurred. Sometimes, it may be due to a simple syntax error or a misunderstanding of how strings work.

Taking the time to understand the issue and troubleshoot the code can help prevent encountering the error in the future.

By following these best practices and familiarizing yourself with string manipulation methods and data types, you can avoid encountering the “Python String Error: ‘str’ Object Does Not Support Item Assignment” and efficiently work with string objects in Python.

FAQ – Frequently asked questions

Here are some commonly asked questions regarding the ‘str’ object item assignment error:

Q: Why am I getting a string error while trying to modify a string?

A: Python string objects are immutable, meaning they cannot be changed once created. Therefore, you cannot modify a string object directly. Instead, you must create a new string object with the desired modifications.

Q: What is an example of an item assignment with a string object?

A: An example of an item assignment with a string object is attempting to change a character in a string by using an index. For instance, if you try to modify the second character in the string ‘hello’ to ‘i’, as in ‘hillo’, you will get the ‘str’ object item assignment error.

Q: How can I modify a string object?

A: There are a few ways to modify a string object, such as using string manipulation functions like replace() or split(), creating a new string with the desired modifications, or converting the string object to a mutable data type like a list and then modifying it.

Q: Can I prevent encountering this error in the future?

A: Yes, here are some best practices to avoid encountering this error: use appropriate data types for the task at hand, understand string immutability, and use string manipulation functions effectively.

Diving deeper into Python data structures and understanding their differences, advantages, and limitations is also helpful.

Q: Why do I need to know about this error?

A: Understanding the ‘str’ object item assignment error is essential for correctly handling and modifying strings in Python.

This error is a common source of confusion and frustration among Python beginners, and resolving it requires a solid understanding of string immutability, data types, and string manipulation functions.

Affiliate links are marked with a *. We receive a commission if a purchase is made.

Programming Languages

Legal information.

Legal Notice

Privacy Policy

Terms and Conditions

© 2024 codingdeeply.com

python dict 'str' object does not support item assignment

Decode Python

Python Tutorials & Tips

How to Fix the Python Error: typeerror: 'str' object does not support item assignment

People come to the Python programming language for a variety of different reasons. It’s highly readable, easy to pick up, and superb for rapid prototyping. But the language’s data types are especially attractive. It’s easy to manipulate Python’s various data types in a number of different ways. Even converting between dissimilar types can be extremely simple. However, some aspects of Python’s data types can be a little counterintuitive. And people working with Python’s strings often find themselves confronted with a “typeerror: ‘str’ object does not support item assignment” error .

The Cause of the Type Error

The “ typeerror : ‘str’ object does not support item assignment” is essentially notifying you that you’re using the wrong technique to modify data within a string. For example, you might have a loop where you’re trying to change the case of the first letter in multiple sentences. If you tried to directly modify the first character of a string it’d give you a typeerror . Because you’re essentially trying to treat an immutable string like a mutable list .

A Deeper Look Into the Type Error

The issue with directly accessing parts of a string can be a little confusing at first. This is in large part thanks to the fact that Python is typically very lenient with variable manipulation. Consider the following Python code.

y = [0,1,2,3,4] y[1] = 2 print(y)

We assign an ordered list of numbers to a variable called y. We can then directly change the value of the number in the second position within the list to 2. And when we print the contents of y we can see that it has indeed been changed. The list assigned to y now reads as [0, 2, 2, 3, 4].

We can access data within a string in the same way we did the list assigned to y. But if we tried to change an element of a string using the same format it would produce the “typeerror: ‘str’ object does not support item assignment”.

There’s a good reason why strings can be accessed but not changed in the same way as other data types in the language. Python’s strings are immutable. There are a few minor exceptions to the rule. But for the most part, modifying strings is essentially digital sleight of hand.

We typically retrieve data from a string while making any necessary modifications, and then assign it to a variable. This is often the same variable the original string was stored in. So we might start with a string in x. We’d then retrieve that information and modify it. And the new string would then be assigned to x. This would overwrite the original contents of x with the modified copy we’d made.

This process does modify the original x string in a functional sense. But technically it’s just creating a new string that’s nearly identical to the old. This can be better illustrated with a few simple examples. These will also demonstrate how to fix the “typeerror: ‘str’ object does not support item assignment” error .

How To Fix the Type Error

We’ll need to begin by recreating the typeerror. Take a look at the following code.

x = “purString” x[0] = “O” print (x)

The code begins by assigning a string to x which reads “purString”. In this example, we can assume that a typo is present and that it should read “OurString”. We can try to fix the typo by replacing the value directly and then printing the correction to the screen. However, doing so produces the “typeerror: ‘str’ object does not support item assignment” error message. This highlights the fact that Python’s strings are immutable. We can’t directly change a character at a specified index within a string variable.

However, we can reference the data in the string and then reassign a modified version of it. Take a look at the following code.

x = “purString” x = “O” + x[1::] print (x)

This is quite similar to the earlier example. We once again begin with the “purString” typo assigned to x. But the following line has some major differences. This line begins by assigning a new value to x. The first part of the assignment specifies that it will be a string, and begin with “O”.

The next part of the assignment is where we see Python’s true relationship with strings. The x[1::] statement reads the data from the original x assignment. However, it begins reading with the first character. Keep in mind that Python’s indexing starts at 0. So the character in the first position is actually “u” rather than “p”. The slice uses : to signify the last character in the string. Essentially, the x[1::] command is shorthand for copying all of the characters in the string which occur after the “p”. However, we began the reassignment of the x variable by creating a new string that starts with “O”. This new string contains “OurString” and assigns it to x.

Again, keep in mind that this functionally replaces the first character in the x string. But on a technical level, we’re accessing x to copy it, modifying the information, and then assigning it to x all over again as a new string. The next line prints x to the screen. The first thing to note when we run this code is that there’s no Python error anymore. But we can also see that the string in x now reads as “OurString”.

  • Errors and Exception

TypeError: ‘str’ object does not support item assignment

Avatar Of Srinivas Ramakrishna

  • November 8, 2022
  • 3 minute read
  • No comments

Table of Contents Hide

How to reproduce the error, solution 1 – create a new string by iterating the old string, solution 2- creating a new string using a list.

In Python, strings are immutable, which means we cannot change certain characters or the text of a string using the assignment operator. If you try to change the string value, the Python interpreter will raise  'str' object does not support item assignment error.

Let us take a simple example to demonstrate this issue.

In the following code, we are accepting a username as an input parameter. If the username consists of non-alphanumeric characters, we are trying to replace those characters in a string with an empty character.

We get the TypeError because we tried to modify the string value using an assignment operator. Since strings are immutable, we cannot replace the value of certain characters of a string using its index and assignment operator.

How to Fix the Error

Since strings are mutable, we need to create a newly updated string to get the desired result. Let us take an example of how a memory allocation happens when we update the string with a new one.

In the above code, notice that when we change the content of the text1 with an updated string, the memory allocation too got updated with a new value; however, the text2 still points to the old memory location.

We can solve this issue in multiple ways. Let us look at a few better solutions to handle the scenarios if we need to update the string characters.

The simplest way to resolve the issue in the demonstration is by creating a new string.

We have a new string called username_modified , which is set to empty initially.

Next, using the for loop, we iterate each character of the string, check if the character is a non-alphanumeric value, and append the character to a new string variable we created.

Another way is to split the string characters into a list, and using the index value of a list; we can change the value of the characters and join them back to a new string.

The  TypeError: 'str' object does not support item assignment   error occurs when we try to change the contents of the string using an assignment operator.

We can resolve this error by creating a new string based on the contents of the old string. We can also convert the string to a list , update the specific characters we need, and join them back into a string.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like

Typeerror: Cannot Unpack Non-Iterable Nonetype Object

[Solved] TypeError: cannot unpack non-iterable NoneType object

Avatar Of Srinivas Ramakrishna

  • September 20, 2022

Python Reverse A List A Step-By-Step Tutorial

  • 2 minute read

Python Reverse a List: A Step-by-Step Tutorial

  • August 20, 2022

Typeerror Only Integer Scalar Arrays Can Be Converted To A Scalar Index

TypeError: only integer scalar arrays can be converted to a scalar index

  • November 24, 2021

How To Rename Columns In Pandas Dataframe

How to rename columns in Pandas DataFrame

Numpy.ndarray.flatten() Function

  • 4 minute read

numpy.ndarray.flatten() function

Python Exponent | Calculate Exponent In Python

Python Exponent | Calculate exponent in Python

python dict 'str' object does not support item assignment

TypeError: NoneType object does not support item assignment

avatar

Last updated: Apr 8, 2024 Reading time · 3 min

banner

# TypeError: NoneType object does not support item assignment

The Python "TypeError: NoneType object does not support item assignment" occurs when we try to perform an item assignment on a None value.

To solve the error, figure out where the variable got assigned a None value and correct the assignment.

typeerror nonetype object does not support item assignment

Here is an example of how the error occurs.

We tried to assign a value to a variable that stores None .

# Checking if the variable doesn't store None

Use an if statement if you need to check if a variable doesn't store a None value before the assignment.

check if variable does not store none

The if block is only run if the variable doesn't store a None value, otherwise, the else block runs.

# Setting a fallback value if the variable stores None

Alternatively, you can set a fallback value if the variable stores None .

setting fallback value if the variable stores none

If the variable stores a None value, we set it to an empty dictionary.

# Track down where the variable got assigned a None value

You have to figure out where the variable got assigned a None value in your code and correct the assignment to a list or a dictionary.

The most common sources of None values are:

  • Having a function that doesn't return anything (returns None implicitly).
  • Explicitly setting a variable to None .
  • Assigning a variable to the result of calling a built-in function that doesn't return anything.
  • Having a function that only returns a value if a certain condition is met.

# Functions that don't return a value return None

Functions that don't explicitly return a value return None .

functions that dont return value return none

You can use the return statement to return a value from a function.

use return statement to return value

The function now returns a list, so we can safely change the value of a list element using square brackets.

# Many built-in functions return None

Note that there are many built-in functions (e.g. sort() ) that mutate the original object in place and return None .

The sort() method mutates the list in place and returns None , so we shouldn't store the result of calling it into a variable.

To solve the error, remove the assignment.

# A function that returns a value only if a condition is met

Another common cause of the error is having a function that returns a value only if a condition is met.

The if statement in the get_list function is only run if the passed-in argument has a length greater than 3 .

To solve the error, you either have to check if the function didn't return None or return a default value if the condition is not met.

Now the function is guaranteed to return a value regardless of whether the condition is met.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • How to Return a default value if None in Python
  • Why does my function print None in Python [Solved]
  • Check if a Variable is or is not None in Python
  • Convert None to Empty string or an Integer in Python
  • How to Convert JSON NULL values to None using Python
  • Join multiple Strings with possibly None values in Python
  • Why does list.reverse() return None in Python

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

Python TypeError: 'str' object does not support item assignment Solution

Posted in PROGRAMMING LANGUAGE /   PYTHON

Python TypeError: 'str' object does not support item assignment Solution

Vinay Khatri Last updated on June 1, 2024

Table of Content

A Python string is a sequence of characters. The string characters are immutable, which means once we have initialized a string with a sequence of characters, we can not change those characters again. This is because the string is an immutable data type.

Similar to the Python list, the Python string also supports indexing, and we can use the index number of an individual character to access that character. But if we try to change the string's character value using indexing, we would receive the TypeError: 'str' object does not support item assignment Error.

This guide discusses the following string error and its solution in detail. It also demonstrates a common example scenario so that you can solve the following error for yourself. Let's get started with the error statement.

Python Problem: TypeError: 'str' object does not support item assignment

The Error TypeError: 'str' object does not support item assignment occur in a Python program when we try to change any character of an initialized string.

Error example

The following error statement has two sub-statements separated with a colon " : " specifying what is wrong with the program.

  • TypeError (Exception Type)
  • 'str' object does not support item assignment

1. TypeError

TypeError is a standard Python exception raised by Python when we perform an invalid operation on an unsupported Python data type .

In the above example, we are receiving this Exception because we tried to assign a new value to the first character of the string " message ". And string characters do not support reassigning. That's why Python raised the TypeError exception.

2.  'str' object does not support item assignment

'str' object does not support item assignment statement is the error message, telling us that we are trying to assign a new character value to the string. And string does not support item assignment.

In the above example, we were trying to change the first character of the string message . And for that, we used the assignment operator on the first character message[0] . And because of the immutable nature of the string, we received the error.

There are many ways to solve the above problem, the easiest way is by converting the string into a list using the list() function. Change the first character and change the list back to the string using the join() method.

Common Example Scenario

Now let's discuss an example scenario where many Python learners commit a mistake in the program and encounter this error.

Error Example

Suppose we need to write a program that accepts a username from the user. And we need to filter that username by removing all the numbers and special characters. The end username should contain only the upper or lowercase alphabets characters.

Error Reason

In the above example, we are getting this error because in line 9 we are trying to change the content of the string username using the assignment operator username[index] = "" .

We can use different techniques to solve the above problems and implement the logic. We can convert the username string to a list, filter the list and then convert it into the string.

Now our code runs successfully, and it also converted our entered admin@123 username to a valid username admin .

In this Python tutorial, we learned what is " TypeError: 'str' object does not support item assignment " Error in Python is and how to debug it. Python raises this error when we accidentally try to assign a new character to the string value. Python string is an immutable data structure and it does not support item assignment operation.

If you are getting a similar error in your program, please check your code and try another way to assign the new item or character to the string. If you are stuck in the following error, you can share your code and query in the comment section. We will try to help you in debugging.

People are also reading:

  • Python List
  • How to Make a Process Monitor in Python?
  • Python TypeError: 'float' object is not iterable Solution
  • String in Python
  • Python typeerror: string indices must be integers Solution
  • Convert Python Files into Standalone Files
  • Sets in Python
  • Python indexerror: list index out of range Solution
  • Wikipedia Data in Python
  • Python TypeError: ‘float’ object is not subscriptable Solution

Vinay

Vinay Khatri I am a Full Stack Developer with a Bachelor's Degree in Computer Science, who also loves to write technical articles that can help fellow developers.

Related Blogs

7 Most Common Programming Errors Every Programmer Should Know

7 Most Common Programming Errors Every Programmer Should Know

Every programmer encounters programming errors while writing and dealing with computer code. They m…

Carbon Programming Language - A Successor to C++

Carbon Programming Language - A Successor to C++

A programming language is a computer language that developers or programmers leverage to …

Introduction to Elixir Programming Language

Introduction to Elixir Programming Language

We know that website development is at its tipping point, as most businesses aim to go digital nowa…

Leave a Comment on this Post

Python Forum

  • View Active Threads
  • View Today's Posts
  • View New Posts
  • My Discussions
  • Unanswered Posts
  • Unread Posts
  • Active Threads
  • Mark all forums read
  • Member List
  • Interpreter

'str' object does not support item assignment

  • Python Forum
  • Python Coding
  • General Coding Help
  • 2 Vote(s) - 3 Average
  • View a Printable Version

User Panel Messages

Announcements.

python dict 'str' object does not support item assignment

Login to Python Forum

TypeError: 'src' object does not support item assignment

The assignment str[i] = str[j] is working inconsistently. Please refer to the screenshots and let me know if I am missing something.

We are receiving TypeError: ‘src’ object does not support item assignment

Regards, Praveen. Thank you!

Please don’t use screenshots. Show the code and the traceback as text.

Strings are immutable. You can’t modify a string by trying to change a character within.

You can create a new string with the bits before, the bits after, and whatever you want in between.

Yeah, you cannot assign a string to a variable, and then modify the string, but you can use the string to create a new one and assign that result to the same variable. Borrowing some code from @BowlOfRed above, you can do this:

Related Topics

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to solve”TypeError: ‘str‘ object does not support item assignment”? #12070

@realkio

realkio commented Sep 1, 2023

@realkio

github-actions bot commented Sep 1, 2023

Sorry, something went wrong.

@glenn-jocher

glenn-jocher commented Sep 1, 2023

  • 👍 1 reaction

github-actions bot commented Oct 2, 2023

@github-actions

No branches or pull requests

@glenn-jocher

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

How to Learn Python from Scratch in 2024

  • Introduction To Python
  • Python 3 basics
  • Important differences between Python 2.x and Python 3.x with examples
  • Download and Install Python 3 Latest Version
  • Statement, Indentation and Comment in Python
  • Python | Set 2 (Variables, Expressions, Conditions and Functions)
  • Global and Local Variables in Python
  • Type Conversion in Python
  • Private Variables in Python
  • __name__ (A Special variable) in Python
  • Taking input in Python
  • Taking multiple inputs from user in Python
  • Python | Output using print() function
  • Python end parameter in print()
  • Python | Output Formatting
  • Python Operators
  • Ternary Operator in Python
  • Operator Overloading in Python
  • Python | a += b is not always a = a + b
  • Difference between == and is operator in Python
  • Python | Set 3 (Strings, Lists, Tuples, Iterations)
  • Python String
  • Python Lists
  • Python Tuples

Python is a general-purpose high-level programming language and is widely used among the developers’ community. Python was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.

Learn Python from Scratch

If you are new to programming and want to learn Python Programming from Scratch, then this complete 2024 guide is here to help you. Whether you are an experienced programmer or new to the programming world, this guide will help you with the knowledge and resources needed to get started with Python Language.

Key features of Python

Python  has many reasons for being popular and in demand. A few of the reasons are mentioned below.

  • Emphasis on  code readability, shorter codes, ease of writing .
  • Programmers can express logical concepts intarted with Pyth  fewer lines of code  in comparison to languages such as C++ or Java.
  • Python  supports multiple programming paradigms , like object-oriented, imperative and functional programming or procedural.
  • It provides  extensive support libraries (Django for web development, Pandas for data analytics etc)
  • Dynamically typed language (Data type is based on value assigned)
  • Philosophy is “Simplicity is the best”.

Application Areas

python-applications

Getting started with Python Programming –

Python is a lot easier to code and learn. Python programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an  online IDE for writing Python codes  or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc. To begin with, writing Python Codes and performing various intriguing and useful operations, one must have Python installed on their System. This can be done by following the step by step instructions provided below:

What if Python already exists? Let’s check

Windows don’t come with Python preinstalled, it needs to be installed explicitly. But unlike windows, most of the Linux OS have Python pre-installed, also macOS comes with Python pre-installed. To check if your device is pre-installed with Python or not, just go to  Command Line (For  Windows , search for  cmd  in the Run dialog( +  R ), for  Linux  open the terminal using  Ctrl+Alt+T , for  macOS  use control+Option+Shift+T .

Now run the following command:

For Python2

For Python3

If Python is already installed, it will generate a message with the Python version available.

learn python

Download and Installation

Before starting with the installation process, you need to download it. For that all versions of Python for Windows, Linux, and MacOS are available on  python.org .

How-to-install-Python-for-windows-11

Download the Python and follow the further instructions for the installation of Python.

Beginning the installation.

python-install-windows-1

How to run a Python program

Let’s consider a simple Hello World Program.

Generally, there are two ways to run a Python program.

  • Using IDEs:  You can use various IDEs(Pycharm, Jupyter Notebook, etc.) which can be used to run Python programs.
  • Using Command-Line:  You can also use command line options to run a Python program. Below steps demonstrate how to run a Python program on Command line in Windows/Unix Operating System:

Open Commandline and then to compile the code type  python HelloWorld.py . If your code has no error then it will execute properly and output will be displayed.

python-hellow-world-windows

Open Terminal of your Unix/Linux OS and then to compile the code type  python HelloWorld.py . If your code has no error then it will execute properly and output will be displayed.

python-linux-hello-world

Fundamentals of Python

Python indentation.

Python uses  indentation  to highlight the blocks of code. Whitespace is used for  indentation  in Python. All statements with the same distance to the right belong to the same block of code. If a block has to be more deeply nested, it is simply indented further to the right. You can understand it better by looking at the following lines of code.

The lines  print(‘Logging on to geeksforgeeks…’)  and  print(‘retype the URL.’)  are two separate code blocks. The two blocks of code in our example if-statement are both indented four spaces. The final  print(‘All set!’)  is not indented, and so it does not belong to the else-block.

Note:  For more information, refer   Indentation in Python .

Python Comments

Comments  are useful information that the developers provide to make the reader understand the source code. It explains the logic or a part of it used in the code. There are two types of comment in Python:

Single line comments:  Python single line comment starts with hashtag symbol with no white spaces.

Multi-line string as comment:  Python multi-line comment is a piece of text enclosed in a delimiter (“””) on each end of the comment.

Note:  For more information, refer   Comments in Python .

Variables  in Python are not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it.

Note:  For more information, refer   Python Variables .

Operators  are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. These operators can be categorized based upon their different functionality:

Arithmetic operators : Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication and division.

Relational Operators:  Relational operators compares the values. It either returns True or False according to the condition.

Logical Operators:  Logical operators perform Logical AND, Logical OR and Logical NOT operations.

Bitwise operators:  Bitwise operator acts on bits and performs bit by bit operation.

Assignment operators: Assignment operators are used to assign values to the variables.

Special operators:  Special operators are of two types-

  • Identity operator that contains  is  and  is not .
  • Membership operator that contains  in  and  not in .

Note:  For more information, refer   Basic Operators in Python .

Basics of Input/Output

Taking input from user –.

Python provides us with two inbuilt functions to read the input from the keyboard.

  • raw_input():  This function works in older version (like Python 2.x). This function takes exactly what is typed from the keyboard, convert it to string and then return it to the variable in which we want to store. For example:
  • input():  This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether the user entered a string or a number or list. For example:

Note:  For more information, refer   Python  input()  and  raw_input() .

Printing output to console –

The simplest way to produce output is using the  print()  function where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string before writing to the screen.

Data types  are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.

Python-data-structure

In Python, numeric data type represent the data which has numeric value. Numeric value can be interger, floating number or even complex numbers. These values are defined as  int ,  float  and  complex  class in Python.

Sequence Type

In Python, a sequence is the ordered collection of similar or different data types. Sequences allow storing multiple values in an organized and efficient fashion. There are several sequence types in Python –

1) String:  A string is a collection of one or more characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character is a string of length one. It is represented by  str  class. Strings in Python can be created using single quotes or double quotes or even triple quotes.

Accessing elements of string –

strings

Deleting/Updating from a String –

In Python, Updation or deletion of characters from a String is not allowed because Strings are immutable. Only new strings can be reassigned to the same name.

Note:  For more information, refer   Python String .

Refer to the below articles to know more about Strings: String Slicing in Python Python String Concatenation Python String Interpolation Python programming questions on String

2) List:   Lists  are just like the arrays, declared in other languages. A single list may contain DataTypes like Integers, Strings, as well as Objects. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. It is represented by  list  class.

Adding Elements to a List:  Using  append() ,  insert()  and  extend()

Accessing elements from the List –

Use the index operator  [ ]  to access an item in a list. In Python, negative sequence indexes represent positions from the end of the array. Instead of having to compute the offset as in  List[len(List)-3] , it is enough to just write  List[-3] .

Removing Elements from the List:  Using  remove()  and  pop()

Note:  For more information, refer   Python List .

Refer to the below articles to know more about List: Iterate over a list in Python Python List Comprehension and Slicing Python programming questions on List

3) Tuple:   Tuple  is an ordered collection of Python objects much like a list. The important difference between a list and a tuple is that tuples are immutable. It is represented by  tuple  class. In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence.

Accessing element of a tuple –

Use the index operator  [ ]  to access an item in a tuple.

Deleting/updating elements of tuple –

Items of a tuple cannot be deleted as tuples are immutable in Python. Only new tuples can be reassigned to the same name.

Note:  For more information, refer   Python Tuples .

Refer to the below articles to know more about tuples: Unpacking a Tuple in Python Operations on Tuples Python programming questions on Tuples

Booleans are data type with one of the two built-in values,  True  or  False . It is denoted by the class bool.

In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements. Sets can be created by using the built-in  set()  function with an iterable object or a sequence by placing the sequence inside curly braces  {} , separated by ‘comma’.

Adding elements:  Using  add()  and  update()

Accessing a Set:  One can loop through the set items using a  for  loop as set items cannot be accessed by referring to an index.

Removing elements from a set:  Using  remove() ,  discard() ,  pop()  and  clear()

Note:  For more information, refer   Python Sets .

Refer to the below articles to know more about Sets: Iterate over a set in Python frozenset() in Python Python programming questions on Sets

Dictionary  in Python is an unordered collection of data values, used to store data values like a map. Dictionary holds  key:value  pair. Each key-value pair in a Dictionary is separated by a colon  : , whereas each key is separated by a ‘comma’. A Dictionary can be created by placing a sequence of elements within curly  {}  braces, separated by ‘comma’.

Nested Dictionary:

Nested-Dictionary

Note:  For more information, refer   Python Nested Dictionary . Adding elements to a Dictionary:  One value at a time can be added to a Dictionary by defining value along with the key e.g.  Dict[Key] = ‘Value’ .

Accessing elements from a Dictionary:  In order to access the items of a dictionary refer to its key name or use  get()  method.

Removing Elements from Dictionary:  Using  pop()  and  popitem()

Note:  For more information, refer   Python Dictionary .

Refer to the below articles to know more about dictionary: Operations on Dictionary Iterate over a dictionary in Python Python programming questions on dictionary

Decision Making

Decision Making in programming is similar to decision making in real life. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

Decision-making statements in Python

  • if statement
  • if..else statements
  • nested if statements
  • if-elif ladder

Example 1:  To demonstrate  if  and  if-else

Example 2:  To demonstrate  nested-if  and  if-elif

Note:  For more information, refer   Decision Making in Python .

Control flow (Loops)

Loops  in programming come into use when we need to repeatedly execute a block of statements. For example: Suppose we want to print “Hello World” 10 times. This can be done with the help of loops. The loops in Python are:

while-loop

Output: Hello Geek Hello Geek Hello Geek 4 3 2 1 11 Note:  For more information, refer   Python While Loops .

for-loop-python

Output: List Iteration geeks for geeks String Iteration G e e k s For-else loop G e e k s No Break G Note:  For more information, refer   Python For Loops .

PythonRange

Output: 0 1 2 3 4 2 3 4 5 6 7 8 15 18 21 24 Note:  For more information, refer   Python range() function .

Refer to the below articles to know more about Loops: Understanding for-loop in Python Backward iteration in Python

Loop control statements

Loop control statements  change execution from its normal sequence. Following are the loop control statements provided by Python:

  • Break:  Break statement in Python is used to bring the control out of the loop when some external condition is triggered.
  • Continue:  Continue statement is opposite to that of break statement, instead of terminating the loop, it forces to execute the next iteration of the loop.
  • Pass:  Pass statement is used to write empty loops. Pass is also used for empty control statement, function and classes.

Note:  For more information, refer   break, continue and pass in Python .

Functions  are generally the block of codes or statements in a program that gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, provides better readability of the code. So basically, a function is a collection of statements that perform some specific task and return the result to the caller. A function can also perform some specific task without returning anything. In Python,  def  keyword is used to create functions.

Function with arguments

  • Default arguments:  A default argument is a parameter that assumes a default value if a value is not provided in the function call for that argument.

Output: ('x: ', 10) ('y: ', 50)

  • Keyword arguments:  The idea is to allow caller to specify argument name with values so that caller does not need to remember order of parameters.

Output: ('Geeks', 'Practice') ('Geeks', 'Practice')

  • Variable length arguments:  In Python a function can also have variable number of arguments. This can be used in the case when we do not know in advance the number of arguments that will be passed into a function.

Output: Hello Welcome to GeeksforGeeks first == Geeks last == Geeks mid == for

Note:  For more information, refer   Functions in Python .

Refer to the below articles to know more about functions: Python Inner Functions Python return statement Call function from another function

Lambda functions

In Python, the  lambda/anonymous  function means that a function is without a name. The  lambda  keyword is used to create anonymous functions. Lambda function can have any number of arguments but has only one expression.

Note:  For more information, refer   Python lambda (Anonymous Functions) .

Refer to the below articles to know more about Lambda: Python programming questions on Lambda

Object Oriented Programming

Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.

Python-OOPS-Concept

Classes and Objects

Class  creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.

An  Object  is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values.

Note:  For more information, refer   Python Classes and Objects .

self  represents the instance of the class. By using the “ self ” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.

Note:  For more information, refer   self in Python class .

Constructors and Destructors

Constructors:  Constructors are generally used for instantiating an object.The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created. In Python the  __init__()  method is called the constructor and is always called when an object is created. There can be two types of constructors:

  • Default constructor:  The constructor which is called implicilty and do not accept any argument.
  • Parameterized constructor: Constructor which is called explicitly with parameters is known as parameterized constructor.

Note:  For more information, refer   Constructors in Python .

Destructors:  Destructors are called when an object gets destroyed. The  __del__()  method is a known as a destructor method in Python. It is called when all references to the object have been deleted i.e when an object is garbage collected.

Note:  For more information, refer   Destructors in Python .

Inheritance

Inheritance is the ability of any class to extract and use features of other classes. It is the process by which new classes called the derived classes are created from existing classes called Base classes.

Note:  For more information, refer   Python inheritance .

Encapsulation

Encapsulation  describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data.

Note:  For more information, refer   Encapsulation in Python .

Polymorphism

Polymorphism  refers to the ability of OOPs programming languages to differentiate between entities with the same name efficiently. This is done by Python with the help of the signature of these entities.

Refer to the articles to know more about OOPS: Bound, unbound, and static methods in Python Multiple inheritance in Python __new__ in Python

File Handling

File handling  is the ability of Python to handle files i.e. to read and write files along with many other file handling options. Python treats files differently as text or binary and this is important. Each line of code includes a sequence of characters and they form a text file. Each line of a file is terminated with a special character, called the  EOL or End of Line characters  like comma  {, }  or newline character.

Basic File Handling operations in Python are:

1) Open a file:  Opening a file refers to getting the file ready either for reading or for writing. This can be done using the  open()  function. This function returns a file object and takes two arguments, one that accepts the file name and another that accepts the mode(Access Mode). Python provides six Access Modes:

Note:  For more information, refer   Open a File in Python .

2) Close the file:   close()  function closes the file and frees the memory space acquired by that file.

3) Reading from a File:  There are three ways to read data from a text file.

  • read():  Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file. File_object.read([n])
  • readline():  Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line. File_object.readline([n])
  • readlines():  Reads all the lines and return them as each line a string element in a list. File_object.readlines()

Let’s suppose the file looks like this:

python-file-handling

Note:  For more information, refer   How to read from a file in Python .

4) Writing to a file:  There are two ways to write in a file.

  • write():  Inserts the string str1 in a single line in the text file. File_object.write(str1)
  • writelines():  For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time. File_object.writelines(L) for L = [str1, str2, str3]

python-writing-to-file

Note:  For more information, refer   Writing to file in Python .

Refer to the below articles to know more about File-Handling: Python seek() function Python tell() function OS Module in Python Programs on OS module

Modules and Packages

A module is a self-contained Python file that contains Python statements and definitions, like a file named  GFG.py , which can be considered as a module named  GFG  which can be imported with the help of  import statement .

Let’s create a simple module named GFG.

To use the above created module, create a new Python file in the same directory and import GFG module using the  import  statement.

Note:  For more information, refer   Python Modules .

Packages are a way of structuring many packages and modules which helps in a well-organized hierarchy of data set, making the directories and modules easy to access.

To create a package in Python, we need to follow these three simple steps:

  • First, we create a directory and give it a package name, preferably related to its operation.
  • Then we put the classes and the required functions in it.
  • Finally we create an  __init__.py  file inside the directory, to let Python know that the directory is a package.

Example:  Let’s create a package for cars.

  • First we create a directory and name it Cars.
  • Finally we create the __init__.py file. This file will be placed inside the Cars directory and can be left blank.

Now, let’s use the package that we created. To do this make a sample.py file in the same directory where Cars package is located and add the following code to it:

python-packages1

Note:  For more information, refer   Create and Access a Python Package .

Regular expressions(RegEx)

Python RegEx  is a powerful text matching tool that uses a pre-defined pattern to match the text. It can identify the presence or absence of text by comparing it to a specific pattern, and it can also divide a pattern into one or more sub-patterns. Below is the list of metacharacters:

The most frequently used methods are:

re.findall():  Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found.

Output: ['123456789', '987654321'] In the above example, metacharacter blackslash  ‘\’  has a very important role as it signals various sequences. If the blackslash is to be used without its special meaning as metacharacter, use ’\\’ .<> \d Matches any decimal digit, this is equivalent to the set class [0-9]. \D Matches any non-digit character. \s Matches any whitespace character. \S Matches any non-whitespace character \w Matches any alphanumeric character, this is equivalent to the class [a-zA-Z0-9_]. \W Matches any non-alphanumeric character.

re.compile():  Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions.

Output: ['e', 'a', 'd', 'b', 'e', 'a']

re.match():  This function attempts to match pattern to whole string. The re.match function returns a match object on success, None on failure.

Output: Given Data: Jun 24 Month: Jun Day: 24 Not a valid date

re.search():  This method either returns None (if the pattern doesn’t match), or a re.MatchObject that contains information about the matching part of the string.

Output: Match at index 14, 21 Full match: June 24 Month: June Day: 24

Note:  For more information, refer   Regular Expression in Python .

Exception handling

Like other languages, Python also provides the runtime errors via  exception handling  method with the help of  try-except .

How try-except works?

  • First try clause is executed i.e. the code between try and except clause.
  • If there is no exception, then only try clause will run, except clause is finished.
  • If any exception occurred, try clause will be skipped and except clause will run.
  • If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception left unhandled, then the execution stops.
  • A try statement can have more than one except clause.

Code 1:  No exception, so try clause will run.

Code 2:  There is an exception so only except clause will run.

Else Clause:  In python, you can also use else clause on try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception.

Raising Exception:  The raise statement allows the programmer to force a specific exception to occur. This must be either an exception instance or an exception class. To know more about the list of exception class   click here .

Note:  For more information, refer   Python exception handling .

author

Please Login to comment...

Similar reads, improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

python3 修改字符串的四种方法 错误 'str' object does not support item assignment 解决方法

python dict 'str' object does not support item assignment

在Python中,字符串是不可变类型,即无法直接修改字符串的某一位字符。

直接修改会报错:'str' object does not support item assignment

 因此改变一个字符串的元素需要新建一个新的字符串。

常见的修改方法有以下4种。

方法1:将字符串转换成列表后修改值,然后用join组成新字符串

方法2: 通过字符串序列切片方式

方法3: 使用字符串的replace函数

方法4: 通过给一个变量赋值(或者重新赋值)

python dict 'str' object does not support item assignment

“相关推荐”对你有帮助么?

python dict 'str' object does not support item assignment

请填写红包祝福语或标题

python dict 'str' object does not support item assignment

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

python dict 'str' object does not support item assignment

  • Python »
  • 3.14.0a0 Documentation »
  • 파이썬 언어 레퍼런스 »
  • Theme Auto Light Dark |

3. 데이터 모델 ¶

3.1. 객체, 값, 형 ¶.

객체 (Objects) 는 파이썬이 데이터(data)를 추상화한 것(abstraction)입니다. 파이썬 프로그램의 모든 데이터는 객체나 객체 간의 관계로 표현됩니다. (폰 노이만(Von Neumann)의 “프로그램 내장식 컴퓨터(stored program computer)” 모델을 따르고, 또 그 관점에서 코드 역시 객체로 표현됩니다.)

Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The is operator compares the identity of two objects; the id() function returns an integer representing its identity.

CPython 구현 상세: CPython 의 경우, id(x) 는 x 가 저장된 메모리의 주소입니다.

객체의 형은 객체가 지원하는 연산들을 정의하고 (예를 들어, “길이를 갖고 있나?”) 그 형의 객체들이 가질 수 있는 가능한 값들을 정의합니다. type() 함수는 객체의 형(이것 역시 객체다)을 돌려줍니다. 아이덴티티와 마찬가지로, 객체의 형 (type) 역시 변경되지 않습니다. [ 1 ]

어떤 객체들의 값 은 변경할 수 있습니다. 값을 변경할 수 있는 객체들을 가변(mutable) 이라고 합니다. 일단 만들어진 후에 값을 변경할 수 없는 객체들을 불변(immutable) 이라고 합니다. (가변 객체에 대한 참조를 저장하고 있는 불변 컨테이너의 값은 가변 객체의 값이 변할 때 변경된다고 볼 수도 있습니다; 하지만 저장하고 있는 객체들의 집합이 바뀔 수 없으므로 컨테이너는 여전히 불변이라고 여겨집니다. 따라서 불변성은 엄밀하게는 변경 불가능한 값을 갖는 것과는 다릅니다. 좀 더 미묘합니다.) 객체의 가변성(mutability)은 그것의 형에 의해 결정됩니다; 예를 들어 숫자, 문자열, 튜플(tuple)은 불변이지만, 딕셔너리(dictionary) 와 리스트(list)는 가변입니다.

객체는 결코 명시적으로 파괴되지 않습니다; 더 참조되지 않을 때(unreachable) 가비지 수거(garbage collect)됩니다. 구현이 가비지 수거를 지연시키거나 아예 생략하는 것이 허락됩니다 — 아직 참조되는 객체들을 수거하지 않는 이상 가비지 수거가 어떤 식으로 구현되는지는 구현의 품질 문제입니다.

CPython 구현 상세: CPython 은 현재 참조 횟수 계산(reference-counting) 방식을 사용하는데, (선택 사항으로) 순환적으로 연결된 가비지의 지연된 감지가 추가됩니다. 이 방법으로 대부분 객체를 참조가 제거되자마자 수거할 수 있습니다. 하지만 순환 참조가 있는 가비지들을 수거한다는 보장은 없습니다. 순환적 가비지 수거의 제어에 관한 정보는 gc 모듈 문서를 참조하면 됩니다. 다른 구현들은 다른 식으로 동작하고, CPython 도 변경될 수 있습니다. 참조가 제거될 때 즉각적으로 파이널리제이션(finalization)되는 것에 의존하지 말아야 합니다 (그래서 항상 파일을 명시적으로 닫아주어야 합니다).

Note that the use of the implementation’s tracing or debugging facilities may keep objects alive that would normally be collectable. Also note that catching an exception with a try … except statement may keep objects alive.

Some objects contain references to “external” resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a close() method. Programs are strongly recommended to explicitly close such objects. The try … finally statement and the with statement provide convenient ways to do this.

어떤 객체들은 다른 객체에 대한 참조를 포함하고 있습니다. 이런 것들을 컨테이너(container) 라고 부릅니다. 튜플, 리스트, 딕셔너리등이 컨테이너의 예입니다. 이 참조들은 컨테이너의 값의 일부입니다. 대부분은, 우리가 컨테이너의 값을 논할 때는, 들어있는 객체들의 아이덴티티 보다는 값을 따집니다. 하지만, 컨테이너의 가변성에 대해 논할 때는 직접 가진 객체들의 아이덴티티만을 따집니다. 그래서, (튜플 같은) 불변 컨테이너가 가변 객체로의 참조를 하고 있다면, 그 가변 객체가 변경되면 컨테이너의 값도 변경됩니다.

형은 거의 모든 측면에서 객체가 동작하는 방법에 영향을 줍니다. 객체의 아이덴티디가 갖는 중요성조차도 어떤 면에서는 영향을 받습니다: 불변형의 경우, 새 값을 만드는 연산은 실제로는 이미 존재하는 객체 중에서 같은 형과 값을 갖는 것을 돌려줄 수 있습니다. 반면에 가변 객체에서는 이런 것이 허용되지 않습니다. 예를 들어, a = 1; b = 1 후에, a 와 b 는 값 1을 갖는 같은 객체일 수도 있고, 아닐 수도 있습니다. 하지만 c = []; d = [] 후에, c 와 d 는 두 개의 서로 다르고, 독립적이고, 새로 만들어진 빈 리스트임이 보장됩니다. ( c = d = [] 는 객은 객체를 c 와 d 에 대입합니다.)

3.2. 표준형 계층 ¶

아래에 파이썬에 내장된 형들의 목록이 있습니다. (구현에 따라 C 나 자바나 다른 언어로 작성된) 확장 모듈들은 추가의 형을 정의할 수 있습니다. 파이썬의 미래 버전 역시 형 계층에 형을 더할 수 있는데 (예를 들어, 유리수, 효율적으로 저장된 정수 배열 등등), 표준 라이브러리를 통해 추가될 가능성이 더 크기는 합니다.

아래에 나오는 몇몇 형에 대한 설명은 ‘특수 어트리뷰트(special attribute)’ 를 나열하는 문단을 포함합니다. 이것들은 구현에 접근할 방법을 제공하는데, 일반적인 사용을 위한 것이 아닙니다. 정의는 앞으로 변경될 수 있습니다.

3.2.1. None ¶

이 형은 하나의 값만을 갖습니다. 이 값을 갖는 하나의 객체가 존재합니다. 이 객체에는 내장된 이름 None 을 통해 접근합니다. 여러 가지 상황에서 값의 부재를 알리는 데 사용됩니다. 예를 들어, 명시적으로 뭔가를 돌려주지 않는 함수의 반환 값입니다. 논리값은 거짓입니다.

3.2.2. NotImplemented ¶

This type has a single value. There is a single object with this value. This object is accessed through the built-in name NotImplemented . Numeric methods and rich comparison methods should return this value if they do not implement the operation for the operands provided. (The interpreter will then try the reflected operation, or some other fallback, depending on the operator.) It should not be evaluated in a boolean context.

더 자세한 내용은 산술 연산 구현 을 참고하십시오.

버전 3.9에서 변경: Evaluating NotImplemented in a boolean context was deprecated.

버전 3.14에서 변경: Evaluating NotImplemented in a boolean context now raises a TypeError . It previously evaluated to True and emitted a DeprecationWarning since Python 3.9.

3.2.3. Ellipsis ¶

이 형은 하나의 값만을 갖습니다. 이 값을 갖는 하나의 객체가 존재합니다. 이 객체에는 리터럴 ... 이나 내장된 이름 Ellipsis 을 통해 접근합니다. 논리값은 참입니다.

3.2.4. numbers.Number ¶

이것들은 숫자 리터럴에 의해 만들어지고, 산술 연산과 내장 산술 함수들이 결과로 돌려줍니다. 숫자 객체는 불변입니다; 한 번 값이 만들어지면 절대 변하지 않습니다. 파이썬의 숫자는 당연히 수학적인 숫자들과 밀접하게 관련되어 있습니다, 하지만 컴퓨터의 숫자 표현상의 제약을 받고 있습니다.

The string representations of the numeric classes, computed by __repr__() and __str__() , have the following properties:

클래스 생성자에 전달될 때 원래 숫자 값을 가진 객체를 생성하는 유효한 숫자 리터럴 입니다.

가능하면, 표현은 10진법입니다.

소수점 앞의 단일 0을 제외하고, 선행 0은 표시되지 않습니다.

소수점 뒤의 단일 0을 제외하고, 후행 0은 표시되지 않습니다.

부호는 숫자가 음수일 때만 표시됩니다.

파이썬은 정수, 실수, 복소수를 구분합니다:

3.2.4.1. numbers.Integral ¶

이것들은 수학적인 정수 집합(양과 음)에 속하는 요소들을 나타냅니다.

정수 표현 규칙은 음수가 포함된 시프트와 마스크 연산에 가장 의미 있는 해석을 제공하기 위한 것입니다.

두 가지 종류의 정수가 있습니다:

이것은 (가상) 메모리가 허락하는 한, 제약 없는 범위의 숫자를 표현합니다. 시프트(shift)와 마스크(mask) 연산이 목적일 때는 이진 표현이 가정되고, 음수는 일종의 2의 보수(2’s complement)로 표현되는데, 부호 비트가 왼쪽으로 무한히 확장된 것과 같은 효과를 줍니다.

이것은 논리값 거짓과 참을 나타냅니다. False 와 True 두 객체만 불린 형 객체입니다. 불린 형은 int 형의 자식형(subtype)이고, 대부분 상황에서 각기 0과1처럼 동작합니다. 예외는 문자열로 변환되는 경우인데, 각기 문자열 "False" 와 "True" 가 반환됩니다.

3.2.4.2. numbers.Real ( float ) ¶

이것들은 기계 수준의 배정도(double precision) 부동 소수점 수를 나타냅니다. 허락되는 값의 범위와 오버플로의 처리에 관해서는 하부 기계의 설계(와 C 나 자바 구현)에 따르는 수밖에 없습니다. 파이썬은 단정도(single precision) 부동 소수점 수를 지원하지 않습니다; 이것들을 사용하는 이유가 되는 프로세서와 메모리의 절감은 파이썬에서 객체를 사용하는데 들어가는 비용과 상쇄되어 미미해집니다. 그 때문에 두 가지 종류의 부동 소수점 수로 언어를 복잡하게 만들만한 가치가 없습니다.

3.2.4.3. numbers.Complex ( complex ) ¶

이것들은 기계 수준 배정도 부동 소수점 수의 쌍으로 복소수를 나타냅니다. 부동 소수점 수와 한계와 문제점을 공유합니다. 복소수 z 의 실수부와 허수부는, 읽기 전용 어트리뷰트 z.real 와 z.imag 로 꺼낼 수 있습니다.

3.2.5. 시퀀스들 ¶

These represent finite ordered sets indexed by non-negative numbers. The built-in function len() returns the number of items of a sequence. When the length of a sequence is n , the index set contains the numbers 0, 1, …, n -1. Item i of sequence a is selected by a[i] . Some sequences, including built-in sequences, interpret negative subscripts by adding the sequence length. For example, a[-2] equals a[n-2] , the second to last item of sequence a with length n .

Sequences also support slicing: a[i:j] selects all items with index k such that i <= k < j . When used as an expression, a slice is a sequence of the same type. The comment above about negative indexes also applies to negative slice positions.

어떤 시퀀스는 세 번째 “스텝(step)” 매개변수를 사용하는 “확장 슬라이싱(extended slicing)”도 지원합니다: a[i:j:k] 는 x = i + n*k , n >= 0 , i <= x < j 를 만족하는 모든 항목 x 를 선택합니다.

시퀀스는 불변성에 따라 구분됩니다

3.2.5.1. 불변 시퀀스 ¶

불변 시퀀스 형의 객체는 일단 만들어진 후에는 변경될 수 없습니다. (만약 다른 객체로의 참조를 포함하면, 그 객체는 가변일 수 있고, 변경될 수 있습니다; 하지만, 불변 객체로부터 참조되는 객체의 집합 자체는 변경될 수 없습니다.)

다음과 같은 형들은 불변 시퀀스입니다:

A string is a sequence of values that represent Unicode code points. All the code points in the range U+0000 - U+10FFFF can be represented in a string. Python doesn’t have a char type; instead, every code point in the string is represented as a string object with length 1 . The built-in function ord() converts a code point from its string form to an integer in the range 0 - 10FFFF ; chr() converts an integer in the range 0 - 10FFFF to the corresponding length 1 string object. str.encode() can be used to convert a str to bytes using the given text encoding, and bytes.decode() can be used to achieve the opposite.

튜플의 항목은 임의의 파이썬 객체입니다. 두 개 이상의 항목으로 구성되는 튜플은 콤마로 분리된 표현식의 목록으로 만들 수 있습니다. 하나의 항목으로 구성된 튜플(싱글턴,singleton)은 표현식에 콤마를 붙여서 만들 수 있습니다(괄호로 표현식을 묶을 수 있으므로, 표현식 만으로는 튜플을 만들지 않습니다). 빈 튜플은 한 쌍의 빈 괄호로 만들 수 있습니다.

바이트열(bytes) 객체는 불변 배열입니다. 항목은 8-비트 바이트인데, 0 <= x < 256 범위의 정수로 표현됩니다. 바이트 객체를 만들 때는 바이트열 리터럴( b'abc' 와 같은) 과 내장 bytes() 생성자(constructor)를 사용할 수 있습니다. 또한, 바이트열 객체는 decode() 메서드를 통해 문자열로 디코딩될 수 있습니다.

3.2.5.2. 가변 시퀀스 ¶

가변 시퀀스는 만들어진 후에 변경될 수 있습니다. 서브스크립션(subscription)과 슬라이싱은 대입문과 del (삭제) 문의 대상으로 사용될 수 있습니다.

The collections and array module provide additional examples of mutable sequence types.

현재 두 개의 내장 가변 시퀀스형이 있습니다:

리스트의 항목은 임의의 파이썬 객체입니다. 리스트는 콤마로 분리된 표현식을 대괄호 안에 넣어서 만들 수 있습니다. (길이 0이나 1의 리스트를 만드는데 별도의 규칙이 필요 없습니다.)

바이트 배열(bytearray) 객체는 가변 배열입니다. 내장 bytearray() 생성자로 만들어집니다. 가변이라는 것(그래서 해싱 불가능하다는 것)을 제외하고, 바이트 배열은 불변 바이트열( bytes ) 객체와 같은 인터페이스와 기능을 제공합니다.

3.2.6. 집합 형들(Set types) ¶

이것들은 중복 없는 불변 객체들의 순서 없고 유한한 집합을 나타냅니다. 인덱싱할 수 없습니다. 하지만 이터레이트할 수 있고, 내장 함수 len() 은 집합 안에 있는 항목들의 개수를 돌려줍니다. 집합의 일반적인 용도는 빠른 멤버십 검사(fast membership testing), 시퀀스에서 중복된 항목 제거, 교집합(intersection), 합집합(union), 차집합(difference), 대칭차집합(symmetric difference)과 같은 집합 연산을 계산하는 것입니다.

집합의 원소들에는 딕셔너리 키와 같은 불변성 규칙이 적용됩니다. 숫자 형의 경우는 숫자 비교에 관한 일반 원칙이 적용된다는 점에 주의해야 합니다: 만약 두 숫자가 같다고 비교되면(예를 들어, 1 과 1.0 ), 그중 하나만 집합에 들어갈 수 있습니다.

현재 두 개의 내장 집합 형이 있습니다:

이것들은 가변 집합을 나타냅니다. 내장 set() 생성자로 만들 수 있고, add() 같은 메서드들을 사용해서 나중에 수정할 수 있습니다.

이것들은 불변 집합을 나타냅니다. 내장 frozenset() 생성자로 만들 수 있습니다. 불변 집합(frozenset)은 불변이고 해시 가능 하므로, 다른 집합의 원소나, 딕셔너리의 키로 사용될 수 있습니다.

3.2.7. 매핑(Mappings) ¶

이것들은 임의의 인덱스 집합으로 인덱싱되는 객체들의 유한한 집합을 나타냅니다. 인덱스 표기법(subscript notation) a[k] 는 매핑 a 에서 k 로 인덱스 되는 항목을 선택합니다; 이것은 표현식에 사용될 수도 있고, 대입이나 del 문장의 대상이 될 수도 있습니다. 내장 함수 len() 은 매핑에 포함된 항목들의 개수를 돌려줍니다.

현재 한 개의 내장 매핑 형이 있습니다:

3.2.7.1. 딕셔너리(Dictionaries) ¶

이것들은 거의 임의의 인덱스 집합으로 인덱싱되는 객체들의 유한한 집합을 나타냅니다. 키로 사용할 수 없는 것들은 리스트, 딕셔너리나 그 외의 가변형 중에서 아이덴티티가 아니라 값으로 비교되는 것들뿐입니다. 딕셔너리의 효율적인 구현이, 키의 해시값이 도중에 변경되지 않고 계속 같은 값으로 유지되도록 요구하고 있기 때문입니다. 키로 사용되는 숫자 형의 경우는 숫자 비교에 관한 일반 원칙이 적용됩니다: 만약 두 숫자가 같다고 비교되면(예를 들어, 1 과 1.0 ), 둘 다 같은 딕셔너리 항목을 인덱싱하는데 사용될 수 있습니다.

딕셔너리는 삽입 순서를 유지합니다, 키가 딕셔너리에 순차적으로 추가된 순서와 같은 순서로 생성됨을 뜻합니다. 기존 키를 교체해도 순서는 변경되지 않지만, 키를 제거했다가 다시 삽입하면 이전 위치를 유지하는 대신 끝에 추가됩니다.

딕셔너리는 가변입니다; {...} 표기법으로 만들 수 있습니다 ( 딕셔너리 디스플레이 섹션을 참고하십시오).

확장 모듈 dbm.ndbm 과 dbm.gnu 는 추가의 매핑 형을 제공하는데, collections 모듈 역시 마찬가지입니다.

버전 3.7에서 변경: 딕셔너리는 3.6 이전의 파이썬 버전에서 삽입 순서를 유지하지 않았습니다. CPython 3.6에서, 삽입 순서가 유지되었지만, 그 시점에는 언어 보증이 아니라 구현 세부 사항으로 간주하였습니다.

3.2.8. 콜러블(Callable types) ¶

이것들은 함수 호출 연산( 호출 섹션 참고)이 적용될 수 있는 형들입니다:

3.2.8.1. 사용자 정의 함수 ¶

사용자 정의 함수 객체는 함수 정의를 통해 만들어집니다 ( 함수 정의 섹션 참고). 함수의 형식 매개변수(formal parameter) 목록과 같은 개수의 항목을 포함하는 인자(argument) 목록으로 호출되어야 합니다.

3.2.8.1.1. Special read-only attributes ¶

3.2.8.1.2. special writable attributes ¶.

Most of these attributes check the type of the assigned value:

Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to functions. Regular attribute dot-notation is used to get and set such attributes.

CPython 구현 상세: CPython’s current implementation only supports function attributes on user-defined functions. Function attributes on built-in functions may be supported in the future.

Additional information about a function’s definition can be retrieved from its code object (accessible via the __code__ attribute).

3.2.8.2. 인스턴스 메서드(Instance methods) ¶

인스턴스 메서드는 클래스, 클래스 인스턴스와 모든 콜러블 객체 (보통 사용자 정의 함수)을 결합합니다.

Special read-only attributes:

Methods also support accessing (but not setting) the arbitrary function attributes on the underlying function object .

User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined function object or a classmethod object.

When an instance method object is created by retrieving a user-defined function object from a class via one of its instances, its __self__ attribute is the instance, and the method object is said to be bound . The new method’s __func__ attribute is the original function object.

When an instance method object is created by retrieving a classmethod object from a class or instance, its __self__ attribute is the class itself, and its __func__ attribute is the function object underlying the class method.

When an instance method object is called, the underlying function ( __func__ ) is called, inserting the class instance ( __self__ ) in front of the argument list. For instance, when C is a class which contains a definition for a function f() , and x is an instance of C , calling x.f(1) is equivalent to calling C.f(x, 1) .

When an instance method object is derived from a classmethod object, the “class instance” stored in __self__ will actually be the class itself, so that calling either x.f(1) or C.f(1) is equivalent to calling f(C,1) where f is the underlying function.

Note that the transformation from function object to instance method object happens each time the attribute is retrieved from the instance. In some cases, a fruitful optimization is to assign the attribute to a local variable and call that local variable. Also notice that this transformation only happens for user-defined functions; other callable objects (and all non-callable objects) are retrieved without transformation. It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this only happens when the function is an attribute of the class.

3.2.8.3. 제너레이터 함수(Generator functions) ¶

A function or method which uses the yield statement (see section yield 문 ) is called a generator function . Such a function, when called, always returns an iterator object which can be used to execute the body of the function: calling the iterator’s iterator.__next__() method will cause the function to execute until it provides a value using the yield statement. When the function executes a return statement or falls off the end, a StopIteration exception is raised and the iterator will have reached the end of the set of values to be returned.

3.2.8.4. 코루틴 함수(Coroutine functions) ¶

async def 를 사용해서 정의되는 함수나 메서드를 코루틴 함수 (coroutine function) 라고 부릅니다. 이런 함수를 호출하면 코루틴 객체를 돌려줍니다. await 표현식을 비롯해, async with 와 async for 문을 사용할 수 있습니다. 코루틴 객체(Coroutine Objects) 섹션을 참조하십시오.

3.2.8.5. 비동기 제너레이터 함수(Asynchronous generator functions) ¶

A function or method which is defined using async def and which uses the yield statement is called a asynchronous generator function . Such a function, when called, returns an asynchronous iterator object which can be used in an async for statement to execute the body of the function.

Calling the asynchronous iterator’s aiterator.__anext__ method will return an awaitable which when awaited will execute until it provides a value using the yield expression. When the function executes an empty return statement or falls off the end, a StopAsyncIteration exception is raised and the asynchronous iterator will have reached the end of the set of values to be yielded.

3.2.8.6. 내장 함수(Built-in functions) ¶

A built-in function object is a wrapper around a C function. Examples of built-in functions are len() and math.sin() ( math is a standard built-in module). The number and type of the arguments are determined by the C function. Special read-only attributes:

__doc__ is the function’s documentation string, or None if unavailable. See function.__doc__ .

__name__ is the function’s name. See function.__name__ .

__self__ is set to None (but see the next item).

__module__ is the name of the module the function was defined in or None if unavailable. See function.__module__ .

3.2.8.7. 내장 메서드(Built-in methods) ¶

This is really a different disguise of a built-in function, this time containing an object passed to the C function as an implicit extra argument. An example of a built-in method is alist.append() , assuming alist is a list object. In this case, the special read-only attribute __self__ is set to the object denoted by alist . (The attribute has the same semantics as it does with other instance methods .)

3.2.8.8. 클래스(Classes) ¶

Classes are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that override __new__() . The arguments of the call are passed to __new__() and, in the typical case, to __init__() to initialize the new instance.

3.2.8.9. 클래스 인스턴스(Class Instances) ¶

Instances of arbitrary classes can be made callable by defining a __call__() method in their class.

3.2.9. 모듈(Modules) ¶

Modules are a basic organizational unit of Python code, and are created by the import system as invoked either by the import statement, or by calling functions such as importlib.import_module() and built-in __import__() . A module object has a namespace implemented by a dictionary object (this is the dictionary referenced by the __globals__ attribute of functions defined in the module). Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.__dict__["x"] . A module object does not contain the code object used to initialize the module (since it isn’t needed once the initialization is done).

어트리뷰트 대입은 모듈의 이름 공간 딕셔너리를 갱신합니다. 예를 들어, m.x = 1 은 m.__dict__["x"] = 1 과 같습니다.

Predefined (writable) attributes:

__name__ The module’s name. __doc__ The module’s documentation string, or None if unavailable. __file__ The pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute may be missing for certain types of modules, such as C modules that are statically linked into the interpreter. For extension modules loaded dynamically from a shared library, it’s the pathname of the shared library file. __annotations__ A dictionary containing variable annotations collected during module body execution. For best practices on working with __annotations__ , please see Annotations Best Practices .

특수 읽기 전용 어트리뷰트들: __dict__ 는 딕셔너리로 표현되는 모듈의 이름 공간입니다.

CPython 구현 상세: CPython 이 모듈 딕셔너리를 비우는 방법 때문에, 딕셔너리에 대한 참조가 남아있더라도, 모듈이 스코프를 벗어나면 모듈 딕셔너리는 비워집니다. 이것을 피하려면, 딕셔너리를 복사하거나 딕셔너리를 직접 이용하는 동안은 모듈을 잡아두어야 합니다.

3.2.10. 사용자 정의 클래스(Custom classes) ¶

Custom class types are typically created by class definitions (see section 클래스 정의 ). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., C.x is translated to C.__dict__["x"] (although there are a number of hooks which allow for other means of locating attributes). When the attribute name is not found there, the attribute search continues in the base classes. This search of the base classes uses the C3 method resolution order which behaves correctly even in the presence of ‘diamond’ inheritance structures where there are multiple inheritance paths leading back to a common ancestor. Additional details on the C3 MRO used by Python can be found at The Python 2.3 Method Resolution Order .

When a class attribute reference (for class C , say) would yield a class method object, it is transformed into an instance method object whose __self__ attribute is C . When it would yield a staticmethod object, it is transformed into the object wrapped by the static method object. See section 디스크립터 구현하기 for another way in which attributes retrieved from a class may differ from those actually contained in its __dict__ .

클래스 어트리뷰트 대입은 클래스의 딕셔너리를 갱신할 뿐, 어떤 경우도 부모 클래스의 딕셔너리를 건드리지는 않습니다.

클래스 객체는 클래스 인스턴스를 돌려주도록(아래를 보십시오) 호출될 수 있습니다(위를 보십시오).

특수 어트리뷰트들(Special attributes):

__name__ The class name. __module__ The name of the module in which the class was defined. __dict__ The dictionary containing the class’s namespace. __bases__ A tuple containing the base classes, in the order of their occurrence in the base class list. __doc__ The class’s documentation string, or None if undefined. __annotations__ A dictionary containing variable annotations collected during class body execution. For best practices on working with __annotations__ , please see Annotations Best Practices . __type_params__ A tuple containing the type parameters of a generic class . __static_attributes__ A tuple containing names of attributes of this class which are accessed through self.X from any function in its body. __firstlineno__ The line number of the first line of the class definition, including decorators.

3.2.11. 클래스 인스턴스(Class instances) ¶

A class instance is created by calling a class object (see above). A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. When an attribute is not found there, and the instance’s class has an attribute by that name, the search continues with the class attributes. If a class attribute is found that is a user-defined function object, it is transformed into an instance method object whose __self__ attribute is the instance. Static method and class method objects are also transformed; see above under “Classes”. See section 디스크립터 구현하기 for another way in which attributes of a class retrieved via its instances may differ from the objects actually stored in the class’s __dict__ . If no class attribute is found, and the object’s class has a __getattr__() method, that is called to satisfy the lookup.

Attribute assignments and deletions update the instance’s dictionary, never a class’s dictionary. If the class has a __setattr__() or __delattr__() method, this is called instead of updating the instance dictionary directly.

어떤 특별한 이름들의 메서드들을 가지면, 클래스 인스턴스는 숫자, 시퀀스, 매핑인 척할 수 있습니다. 특수 메서드 이름들 섹션을 보십시오.

특수 어트리뷰트들: __dict__ 는 어트리뷰트 딕셔너리입니다; __class__ 는 인스턴스의 클래스입니다.

3.2.12. I/O 객체 (파일 객체라고도 알려져 있습니다) ¶

파일 객체 는 열린 파일을 나타냅니다. 파일 객체를 만드는 여러 가지 단축법이 있습니다: open() 내장 함수, os.popen() , os.fdopen() 과 소켓 객체의 makefile() 메서드 (그리고, 아마도 확장 모듈들이 제공하는 다른 함수들이나 메서드들).

sys.stdin , sys.stdout , sys.stderr 는 인터프리터의 표준 입력, 출력, 에러 스트림으로 초기화된 파일 객체들입니다; 모두 텍스트 모드로 열려서 io.TextIOBase 추상 클래스에 의해 정의된 인터페이스를 따릅니다.

3.2.13. 내부 형(Internal types) ¶

인터프리터가 내부적으로 사용하는 몇몇 형들은 사용자에게 노출됩니다. 인터프리터의 미래 버전에서 이들의 정의는 변경될 수 있지만, 완전함을 위해 여기서 언급합니다.

3.2.13.1. 코드 객체(Code objects) ¶

코드 객체는 바이트로 컴파일된(byte-compiled) 실행 가능한 파이썬 코드를 나타내는데, 그냥 바이트 코드 라고도 부릅니다. 코드 객체와 함수 객체 간에는 차이가 있습니다; 함수 객체는 함수의 전역 공간(globals) (함수가 정의된 모듈)을 명시적으로 참조하고 있지만, 코드 객체는 어떤 문맥(context)도 갖고 있지 않습니다; 또한 기본 인자값들이 함수 객체에 저장되어 있지만 코드 객체에는 들어있지 않습니다 (실행 시간에 계산되는 값들을 나타내기 때문입니다). 함수 객체와는 달리, 코드 객체는 불변이고 가변 객체들에 대한 어떤 참조도 (직접 혹은 간접적으로도) 갖고 있지 않습니다.

3.2.13.1.1. Special read-only attributes ¶

The following flag bits are defined for co_flags : bit 0x04 is set if the function uses the *arguments syntax to accept an arbitrary number of positional arguments; bit 0x08 is set if the function uses the **keywords syntax to accept arbitrary keyword arguments; bit 0x20 is set if the function is a generator. See 코드 객체 비트 플래그 for details on the semantics of each flags that might be present.

Future feature declarations ( from __future__ import division ) also use bits in co_flags to indicate whether a code object was compiled with a particular feature enabled: bit 0x2000 is set if the function was compiled with future division enabled; bits 0x10 and 0x1000 were used in earlier versions of Python.

Other bits in co_flags are reserved for internal use.

If a code object represents a function, the first item in co_consts is the documentation string of the function, or None if undefined.

3.2.13.1.2. Methods on code objects ¶

Returns an iterable over the source code positions of each bytecode instruction in the code object.

The iterator returns tuple s containing the (start_line, end_line, start_column, end_column) . The i-th tuple corresponds to the position of the source code that compiled to the i-th instruction. Column information is 0-indexed utf-8 byte offsets on the given source line.

This positional information can be missing. A non-exhaustive lists of cases where this may happen:

Running the interpreter with -X no_debug_ranges .

Loading a pyc file compiled while using -X no_debug_ranges .

Position tuples corresponding to artificial instructions.

Line and column numbers that can’t be represented due to implementation specific limitations.

When this occurs, some or all of the tuple elements can be None .

Added in version 3.11.

This feature requires storing column positions in code objects which may result in a small increase of disk usage of compiled Python files or interpreter memory usage. To avoid storing the extra information and/or deactivate printing the extra traceback information, the -X no_debug_ranges command line flag or the PYTHONNODEBUGRANGES environment variable can be used.

Returns an iterator that yields information about successive ranges of bytecode s. Each item yielded is a (start, end, lineno) tuple :

start (an int ) represents the offset (inclusive) of the start of the bytecode range

end (an int ) represents the offset (exclusive) of the end of the bytecode range

lineno is an int representing the line number of the bytecode range, or None if the bytecodes in the given range have no line number

The items yielded will have the following properties:

The first range yielded will have a start of 0.

The (start, end) ranges will be non-decreasing and consecutive. That is, for any pair of tuple s, the start of the second will be equal to the end of the first.

No range will be backwards: end >= start for all triples.

The last tuple yielded will have end equal to the size of the bytecode .

Zero-width ranges, where start == end , are allowed. Zero-width ranges are used for lines that are present in the source code, but have been eliminated by the bytecode compiler.

Added in version 3.10.

The PEP that introduced the co_lines() method.

Return a copy of the code object with new values for the specified fields.

Code objects are also supported by the generic function copy.replace() .

Added in version 3.8.

3.2.13.2. 프레임 객체(Frame objects) ¶

Frame objects represent execution frames. They may occur in traceback objects , and are also passed to registered trace functions.

3.2.13.2.1. Special read-only attributes ¶

3.2.13.2.2. special writable attributes ¶, 3.2.13.2.3. frame object methods ¶.

프레임 객체는 한가지 메서드를 지원합니다:

This method clears all references to local variables held by the frame. Also, if the frame belonged to a generator , the generator is finalized. This helps break reference cycles involving frame objects (for example when catching an exception and storing its traceback for later use).

RuntimeError is raised if the frame is currently executing or suspended.

Added in version 3.4.

버전 3.13에서 변경: Attempting to clear a suspended frame raises RuntimeError (as has always been the case for executing frames).

3.2.13.3. 트레이스백 객체(Traceback objects) ¶

Traceback objects represent the stack trace of an exception . A traceback object is implicitly created when an exception occurs, and may also be explicitly created by calling types.TracebackType .

버전 3.7에서 변경: Traceback objects can now be explicitly instantiated from Python code.

For implicitly created tracebacks, when the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. When an exception handler is entered, the stack trace is made available to the program. (See section try 문 .) It is accessible as the third item of the tuple returned by sys.exc_info() , and as the __traceback__ attribute of the caught exception.

When the program contains no suitable handler, the stack trace is written (nicely formatted) to the standard error stream; if the interpreter is interactive, it is also made available to the user as sys.last_traceback .

For explicitly created tracebacks, it is up to the creator of the traceback to determine how the tb_next attributes should be linked to form a full stack trace.

The line number and last instruction in the traceback may differ from the line number of its frame object if the exception occurred in a try statement with no matching except clause or with a finally clause.

The special writable attribute tb_next is the next level in the stack trace (towards the frame where the exception occurred), or None if there is no next level.

버전 3.7에서 변경: This attribute is now writable

3.2.13.4. 슬라이스 객체(Slice objects) ¶

Slice objects are used to represent slices for __getitem__() methods. They are also created by the built-in slice() function.

특수 읽기 전용 어트리뷰트들: start 는 하한(lower bound) 입니다; stop 은 상한(upper bound) 입니다; step 은 스텝 값입니다; 각 값은 생략될 경우 None 입니다. 이 어트리뷰트들은 임의의 형이 될 수 있습니다.

슬라이스 객체는 하나의 메서드를 지원합니다.

이 메서드는 하나의 정수 인자 length 를 받아서 슬라이스 객체가 길이 length 인 시퀀스에 적용되었을 때 그 슬라이스에 대한 정보를 계산합니다. 세 개의 정수로 구성된 튜플을 돌려줍니다: 이것들은 각각 start 와 stop 인덱스와, step 또는 슬라이스의 스트라이드(stride) 길이입니다. 생략되었거나 범위를 벗어난 인덱스들은 일반적인 슬라이스와 같은 방법으로 다뤄집니다.

3.2.13.5. 스태틱 메서드 객체(Static method objects) ¶

Static method objects provide a way of defeating the transformation of function objects to method objects described above. A static method object is a wrapper around any other object, usually a user-defined method object. When a static method object is retrieved from a class or a class instance, the object actually returned is the wrapped object, which is not subject to any further transformation. Static method objects are also callable. Static method objects are created by the built-in staticmethod() constructor.

3.2.13.6. 클래스 메서드 객체(Class method objects) ¶

A class method object, like a static method object, is a wrapper around another object that alters the way in which that object is retrieved from classes and class instances. The behaviour of class method objects upon such retrieval is described above, under “instance methods” . Class method objects are created by the built-in classmethod() constructor.

3.3. 특수 메서드 이름들 ¶

A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading , allowing classes to define their own behavior with respect to language operators. For instance, if a class defines a method named __getitem__() , and x is an instance of this class, then x[i] is roughly equivalent to type(x).__getitem__(x, i) . Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined (typically AttributeError or TypeError ).

Setting a special method to None indicates that the corresponding operation is not available. For example, if a class sets __iter__() to None , the class is not iterable, so calling iter() on its instances will raise a TypeError (without falling back to __getitem__() ). [ 2 ]

내장형을 흉내 내는 클래스를 구현할 때, 모방은 모형화하는 객체에 말이 되는 수준까지만 구현하는 것이 중요합니다. 예를 들어, 어떤 시퀀스는 개별 항목들을 꺼내는 것만으로도 잘 동작할 수 있습니다. 하지만 슬라이스를 꺼내는 것은 말이 안 될 수 있습니다. (이런 한가지 예는 W3C의 Document Object Model의 NodeList 인터페이스입니다.)

3.3.1. 기본적인 커스터마이제이션 ¶

클래스 cls 의 새 인스턴스를 만들기 위해 호출됩니다. __new__() 는 스태틱 메서드입니다 (그렇게 선언하지 않아도 되는 특별한 경우입니다)인데, 첫 번째 인자로 만들려고 하는 인스턴스의 클래스가 전달됩니다. 나머지 인자들은 객체 생성자 표현(클래스 호출)에 전달된 것들입니다. __new__() 의 반환 값은 새 객체 인스턴스이어야 합니다 (보통 cls 의 인스턴스).

Typical implementations create a new instance of the class by invoking the superclass’s __new__() method using super().__new__(cls[, ...]) with appropriate arguments and then modifying the newly created instance as necessary before returning it.

If __new__() is invoked during object construction and it returns an instance of cls , then the new instance’s __init__() method will be invoked like __init__(self[, ...]) , where self is the new instance and the remaining arguments are the same as were passed to the object constructor.

만약 __new__() 가 cls 의 인스턴스를 돌려주지 않으면, 새 인스턴스의 __init__() 는 호출되지 않습니다.

__new__() 는 주로 불변형(int, str, tuple과 같은)의 서브 클래스가 인스턴스 생성을 커스터마이즈할 수 있도록 하는 데 사용됩니다. 또한, 사용자 정의 메타 클래스에서 클래스 생성을 커스터마이즈하기 위해 자주 사용됩니다.

( __new__() 에 의해) 인스턴스가 만들어진 후에, 하지만 호출자에게 돌려주기 전에 호출됩니다. 인자들은 클래스 생성자 표현으로 전달된 것들입니다. 만약 베이스 클래스가 __init__() 메서드를 갖고 있다면, 서브 클래스의 __init__() 메서드는, 있다면, 인스턴스에서 베이스 클래스가 차지하는 부분이 올바르게 초기화됨을 확실히 하기 위해 명시적으로 호출해주어야 합니다; 예를 들어: super().__init__([args...]) .

객체를 만드는데 __new__() 와 __init__() 가 협력하고 있으므로 ( __new__() 는 만들고, __init__() 는 그것을 커스터마이즈합니다), __init__() 가 None 이외의 값을 돌려주면 실행시간에 TypeError 를 일으킵니다.

인스턴스가 파괴되기 직전에 호출됩니다. 파이널라이저 또는 (부적절하게) 파괴자라고 불립니다. 만약 베이스 클래스가 __del__() 메서드를 갖고 있다면, 자식 클래스의 __del__() 메서드는, 정의되어 있다면, 인스턴스에서 베이스 클래스가 차지하는 부분을 적절하게 삭제하기 위해, 명시적으로 베이스 클래스의 메서드를 호출해야 합니다.

(권장하지는 않지만!) __del__() 메서드는 인스턴스에 대한 새로운 참조를 만듦으로써 인스턴스의 파괴를 지연시킬 수 있습니다. 이것을 객체 부활 이라고 부릅니다. 부활한 객체가 파괴될 때 __del__() 이 두 번째로 호출될지는 구현에 따라 다릅니다; 현재 CPython 구현은 오직 한 번만 호출합니다.

인터프리터가 종료할 때 아직 남아있는 객체들에 대해서는 __del__() 메서드의 호출이 보장되지 않습니다.

del x 는 직접 x.__del__() 를 호출하지 않습니다 — 앞에 있는 것은 x 의 참조 횟수(reference count)를 하나 감소시키고, 뒤에 있는 것은 x 의 참조 횟수가 0 이 될 때 호출됩니다.

CPython 구현 상세: It is possible for a reference cycle to prevent the reference count of an object from going to zero. In this case, the cycle will be later detected and deleted by the cyclic garbage collector . A common cause of reference cycles is when an exception has been caught in a local variable. The frame’s locals then reference the exception, which references its own traceback, which references the locals of all frames caught in the traceback.

gc 모듈에 대한 문서.

__del__() 이 호출되는 불안정한 상황 때문에, 이것이 실행 중에 발생시키는 예외는 무시되고, 대신에 sys.stderr 로 경고가 출력됩니다. 특히:

__del__() 은 (임의의 스레드에서) 임의의 코드가 실행되는 동안 호출될 수 있습니다. __del__() 이 록을 얻어야 하거나 다른 블로킹 자원을 호출하면, __del__() 을 실행하기 위해 중단된 코드가 자원을 이미 차지했을 수 있으므로 교착 상태에 빠질 수 있습니다.

__del__() 은 인터프리터를 종료할 때 실행될 수 있습니다. 결과적으로, 액세스해야 하는 전역 변수(다른 모듈 포함)가 이미 삭제되었거나 None 으로 설정되었을 수 있습니다. 파이썬은 이름이 하나의 밑줄로 시작하는 전역 객체가 다른 전역 객체들보다 먼저 삭제됨을 보장합니다; 이것은, 만약 그 전역 객체들에 대한 다른 참조가 존재하지 않는다면, __del__() 메서드가 호출되는 시점에, 임포트된 모듈들이 남아있도록 확실히 하는 데 도움이 될 수 있습니다.

repr() 내장 함수에 의해 호출되어 객체의 “형식적인(official)” 문자열 표현을 계산합니다. 만약 가능하다면, 이것은 같은 (적절한 환경이 주어질 때) 값을 갖는 객체를 새로 만들 수 있는 올바른 파이썬 표현식처럼 보여야 합니다. 가능하지 않다면, <...쓸모있는 설명...> 형태의 문자열을 돌려줘야 합니다. 반환 값은 반드시 문자열이어야 합니다. 만약 클래스가 __str__() 없이 __repr__() 만 정의한다면, __repr__() 은 그 클래스 인스턴스의 “비형식적인(informal)” 문자열 표현이 요구될 때 사용될 수 있습니다.

이것은 디버깅에 사용되기 때문에, 표현이 풍부한 정보를 담고 모호하지 않게 하는 것이 중요합니다.

str(object) 와 내장 함수 format() , print() 에 의해 호출되어 객체의 “비형식적인(informal)” 또는 보기 좋게 인쇄 가능한 문자열 표현을 계산합니다. 반환 값은 반드시 문자열 객체여야 합니다.

이 메서드는 __str__() 이 올바른 파이썬 표현식을 돌려줄 것이라고 기대되지 않는다는 점에서 object.__repr__() 과 다릅니다: 더 편리하고 간결한 표현이 사용될 수 있습니다.

내장형 object 에 정의된 기본 구현은 object.__repr__() 을 호출합니다.

bytes 에 의해 호출되어 객체의 바이트열 표현을 계산합니다. 반환 값은 반드시 bytes 객체여야 합니다.

format() 내장 함수, 확대하면, 포맷 문자열 리터럴(formatted string literals) 의 계산과 str.format() 메서드에 의해 호출되어, 객체의 “포맷된” 문자열 표현을 만들어냅니다. format_spec 인자는 요구되는 포맷 옵션들을 포함하는 문자열입니다. format_spec 인자의 해석은 __format__() 을 구현하는 형에 달려있으나, 대부분 클래스는 포매팅을 내향형들의 하나로 위임하거나, 비슷한 포맷 옵션 문법을 사용합니다.

표준 포매팅 문법에 대해서는 포맷 명세 미니 언어 를 참고하면 됩니다.

반환 값은 반드시 문자열이어야 합니다.

버전 3.4에서 변경: object 의 __format__ 메서드 자신은, 빈 문자열이 아닌 인자가 전달되면 TypeError 를 발생시킵니다.

버전 3.7에서 변경: 이제 object.__format__(x, '') 는 format(str(x), '') 가 아니라 str(x) 와 동등합니다.

이것들은 소위 “풍부한 비교(rich comparison)” 메서드입니다. 연산자 기호와 메서드 이름 간의 관계는 다음과 같습니다: x<y 는 x.__lt__(y) 를 호출합니다, x<=y 는 x.__le__(y) 를 호출합니다, x==y 는 x.__eq__(y) 를 호출합니다, x!=y 는 x.__ne__(y) 를 호출합니다, x>y 는 x.__gt__(y) 를 호출합니다, x>=y 는 x.__ge__(y) 를 호출합니다.

A rich comparison method may return the singleton NotImplemented if it does not implement the operation for a given pair of arguments. By convention, False and True are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.

By default, object implements __eq__() by using is , returning NotImplemented in the case of a false comparison: True if x is y else NotImplemented . For __ne__() , by default it delegates to __eq__() and inverts the result unless it is NotImplemented . There are no other implied relationships among the comparison operators or default implementations; for example, the truth of (x<y or x==y) does not imply x<=y . To automatically generate ordering operations from a single root operation, see functools.total_ordering() .

사용자 정의 비교 연산자를 지원하고 딕셔너리 키로 사용될 수 있는 해시 가능 객체를 만드는 것에 관한 몇 가지 중요한 내용이 __hash__() 에 관한 문단에 나옵니다.

There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are their own reflection. If the operands are of different types, and the right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. Virtual subclassing is not considered.

When no appropriate method returns any value other than NotImplemented , the == and != operators will fall back to is and is not , respectively.

Called by built-in function hash() and for operations on members of hashed collections including set , frozenset , and dict . The __hash__() method should return an integer. The only required property is that objects which compare equal have the same hash value; it is advised to mix together the hash values of the components of the object that also play a part in comparison of objects by packing them into a tuple and hashing the tuple. Example:

hash() 는 객체가 정의한 __hash__() 메서드가 돌려주는 값을 Py_ssize_t 의 크기로 자릅니다(truncate). 이것은 보통 64-bit 빌드에서는 8바이트고, 32-bit 빌드에서는 4바이트입니다. 만약 객체의 __hash__() 가 서로 다른 비트 크기를 갖는 빌드들 사이에서 함께 사용되어야 한다면, 모든 지원할 빌드들에서의 폭을 검사해야 합니다. 이렇게 하는 쉬운 방법은 python -c "import sys; print(sys.hash_info.width)" 입니다.

If a class does not define an __eq__() method it should not define a __hash__() operation either; if it defines __eq__() but not __hash__() , its instances will not be usable as items in hashable collections. If a class defines mutable objects and implements an __eq__() method, it should not implement __hash__() , since the implementation of hashable collections requires that a key’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).

사용자 정의 클래스는 기본적으로 __eq__() 와 __hash__() 메서드를 갖습니다; 모든 객체는 (자기 자신을 제외하고) 같지 않다고 비교되고, x.__hash__() 는 적절한 값을 돌려주어, x == y 일 때 x is y 와 hash(x) == hash(y) 가 동시에 성립할 수 있도록 합니다.

__eq__() 를 재정의하고 __hash__() 를 정의하지 않는 클래스는 __hash__() 가 None 으로 설정됩니다. 클래스의 __hash__() 메서드가 None 이면, 클래스의 인스턴스는 프로그램이 해시값을 얻으려 시도할 때 TypeError 를 일으키고, isinstance(obj, collections.abc.Hashable) 로 검사할 때 해시 가능하지 않다고 올바로 감지됩니다.

만약 __eq__() 를 재정의하는 클래스가 부모 클래스로부터 __hash__() 의 구현을 물려받고 싶으면 인터프리터에게 명시적으로 이렇게 지정해주어야 합니다: __hash__ = <ParentClass>.__hash__ .

만약 __eq__() 를 재정의하지 않는 클래스가 해시 지원을 멈추고 싶으면, 클래스 정의에 __hash__ = None 을 포함해야 합니다. 자신의 __hash__() 을 정의한 후에 직접 TypeError 를 일으키는 경우는 isinstance(obj, collections.abc.Hashable) 호출이 해시 가능하다고 잘못 인식합니다.

기본적으로, str과 bytes 객체들의 __hash__() 값은 예측할 수 없는 난수값으로 “솔트되어(salted)” 있습니다. 개별 파이썬 프로세스 내에서는 변하지 않는 값으로 유지되지만, 파이썬을 반복적으로 실행할 때는 예측할 수 없게 됩니다.

This is intended to provide protection against a denial-of-service caused by carefully chosen inputs that exploit the worst case performance of a dict insertion, O ( n 2 ) complexity. See http://ocert.org/advisories/ocert-2011-003.html for details.

해시값의 변경은 집합의 이터레이션 순서에 영향을 줍니다, 파이썬은 이 순서에 대해 어떤 보장도 하지 않습니다 (그리고 보통 32-bit 와 64-bit 빌드 사이에서도 다릅니다).

PYTHONHASHSEED 를 참고하십시오.

버전 3.3에서 변경: 해시 난수 화는 기본적으로 활성화됩니다.

Called to implement truth value testing and the built-in operation bool() ; should return False or True . When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__() , all its instances are considered true.

3.3.2. 어트리뷰트 액세스 커스터마이제이션 ¶

클래스 인스턴스의 어트리뷰트 참조(읽기, 대입하기, x.name 을 삭제하기)의 의미를 변경하기 위해 다음과 같은 메서드들이 정의될 수 있습니다.

기본 어트리뷰트 액세스가 AttributeError 로 실패할 때 호출됩니다 ( name 이 인스턴스 어트리뷰트 또는 self 의 클래스 트리에 있는 어트리뷰트가 아니라서 __getattribute__() 가 AttributeError 를 일으키거나; name 프로퍼티의 __get__() 이 AttributeError 를 일으킬 때). 이 메서드는 (계산된) 어트리뷰트 값을 반환하거나 AttributeError 예외를 일으켜야 합니다.

Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__() .) This is done both for efficiency reasons and because otherwise __getattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can take total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control over attribute access.

클래스 인스턴스의 어트리뷰트 액세스를 구현하기 위해 조건 없이 호출됩니다. 만약 클래스가 __getattr__() 도 함께 구현하면, __getattribute__() 가 명시적으로 호출하거나 AttributeError 를 일으키지 않는 이상 __getattr__ 는 호출되지 않습니다. 이 메서드는 어트리뷰트의 (계산된) 값을 돌려주거나 AttributeError 예외를 일으켜야 합니다. 이 메서드에서 무한 재귀(infinite recursion)가 발생하는 것을 막기 위해, 구현은 언제나 필요한 어트리뷰트에 접근하기 위해 같은 이름의 베이스 클래스의 메서드를 호출해야 합니다. 예를 들어, object.__getattribute__(self, name) .

This method may still be bypassed when looking up special methods as the result of implicit invocation via language syntax or built-in functions . See 특수 메서드 조회 .

인자 obj , name 으로 감사 이벤트 object.__getattr__ 을 발생시킵니다.

어트리뷰트 대입이 시도될 때 호출됩니다. 일반적인 메커니즘(즉 인스턴스 딕셔너리에 값을 저장하는 것) 대신에 이것이 호출됩니다. name 은 어트리뷰트 이름이고, value 는 그것에 대입하려는 값입니다.

__setattr__() 에서 인스턴스 어트리뷰트에 대입하려고 할 때는, 같은 이름의 베이스 클래스의 메서드를 호출해야 합니다. 예를 들어 object.__setattr__(self, name, value)

인자 obj , name , value 로 감사 이벤트 object.__setattr__ 을 발생시킵니다.

__setattr__() 과 비슷하지만 어트리뷰트를 대입하는 대신에 삭제합니다. 이것은 del obj.name 이 객체에 의미가 있는 경우에만 구현되어야 합니다.

인자 obj , name 으로 감사 이벤트 object.__delattr__ 을 발생시킵니다.

Called when dir() is called on the object. An iterable must be returned. dir() converts the returned iterable to a list and sorts it.

3.3.2.1. 모듈 어트리뷰트 액세스 커스터마이제이션 ¶

특수한 이름 __getattr__ 과 __dir__ 는 모듈 어트리뷰트에 대한 접근을 사용자 정의하는 데 사용될 수도 있습니다. 모듈 수준의 __getattr__ 함수는 하나의 인자로 어트리뷰트의 이름을 받아서 계산된 값을 돌려주거나 AttributeError 를 발생시켜야 합니다. 일반적인 조회(즉 object.__getattribute__() )를 통해 어트리뷰트가 모듈 객체에서 발견되지 않으면, AttributeError 를 일으키기 전에 모듈 __dict__ 에서 __getattr__ 을 검색합니다. 발견되면, 어트리뷰트 이름으로 그 함수를 호출하고 결과를 돌려줍니다.

The __dir__ function should accept no arguments, and return an iterable of strings that represents the names accessible on module. If present, this function overrides the standard dir() search on a module.

모듈 동작(어트리뷰트 설정, 프로퍼티 등)을 보다 세밀하게 사용자 정의하려면, 모듈 객체의 __class__ 어트리뷰트를 types.ModuleType 의 서브 클래스로 설정할 수 있습니다. 예를 들면:

모듈 __getattr__ 정의와 모듈 __class__ 설정은 어트리뷰트 액세스 구문을 사용하는 조회에만 영향을 미칩니다 – 모듈 전역에 대한 직접적인 액세스(모듈 내의 코드에 의한 액세스이거나 모듈의 전역 딕셔너리에 대한 참조를 거치거나)는 영향받지 않습니다.

버전 3.5에서 변경: 이제 __class__ 모듈 어트리뷰트가 쓰기 가능합니다.

Added in version 3.7: __getattr__ 과 __dir__ 모듈 어트리뷰트.

모듈에 대한 __getattr__ 과 __dir__ 함수를 설명합니다.

3.3.2.2. 디스크립터 구현하기 ¶

다음에 오는 메서드들은 메서드를 가진 클래스(소위 디스크립터(descriptor) 클래스)의 인스턴스가 소유자(owner) 클래스에 등장할 때만 적용됩니다(디스크립터는 소유자 클래스의 딕셔너리나 그 부모 클래스 중 하나의 딕셔너리에 있어야 합니다). 아래의 예에서, “어트리뷰트” 는 이름이 소유자 클래스의 __dict__ 의 키로 사용되고 있는 어트리뷰트를 가리킵니다.

소유자 클래스(클래스 어트리뷰트 액세스) 나 그 클래스의 인스턴스(인스턴스 어트리뷰트 액세스)의 어트리뷰트를 취하려고 할 때 호출됩니다. 선택적 owner 인자는 소유자 클래스입니다. 반면에 instance 는 어트리뷰트 참조가 일어나고 있는 인스턴스이거나, 어트리뷰트가 owner 를 통해 액세스 되는 경우 None 입니다.

이 메서드는 계산된 어트리뷰트 값을 돌려주거나 AttributeError 예외를 일으켜야 합니다.

PEP 252 는 __get__() 이 하나나 두 개의 인자를 갖는 콜러블이라고 지정합니다. 파이썬 자신의 내장 디스크립터는 이 명세를 지원합니다; 그러나, 일부 제삼자 도구에는 두 인수를 모두 요구하는 디스크립터가 있을 수 있습니다. 파이썬 자신의 __getattribute__() 구현은 필요한지와 관계없이 항상 두 인자를 모두 전달합니다.

소유자 클래스의 인스턴스 instance 의 어트리뷰트를 새 값 value 로 설정할 때 호출됩니다.

__set__() 이나 __delete__() 를 추가하면 디스크립터 유형이 “데이터 디스크립터(data descriptor)”로 변경됨에 유의하십시오. 자세한 내용은 디스크립터 호출하기 를 참조하십시오.

소유자 클래스의 인스턴스 instance 의 어트리뷰트를 삭제할 때 호출됩니다.

Instances of descriptors may also have the __objclass__ attribute present:

The attribute __objclass__ is interpreted by the inspect module as specifying the class where this object was defined (setting this appropriately can assist in runtime introspection of dynamic class attributes). For callables, it may indicate that an instance of the given type (or a subclass) is expected or required as the first positional argument (for example, CPython sets this attribute for unbound methods that are implemented in C).

3.3.2.3. 디스크립터 호출하기 ¶

In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol: __get__() , __set__() , and __delete__() . If any of those methods are defined for an object, it is said to be a descriptor.

어트리뷰트 액세스의 기본 동작은 객체의 딕셔너리에서 어트리뷰트를 읽고, 쓰고, 삭제하는 것입니다. 예를 들어 a.x 는 a.__dict__['x'] 에서 시작해서 type(a).__dict__['x'] 를 거쳐 type(a) 의 메타 클래스를 제외한 베이스 클래스들을 거쳐 가는 일련의 조회로 구성됩니다.

그러나, 만약 조회한 값이 디스크립터 메서드를 구현한 객체면, 파이썬은 기본 동작 대신에 디스크립터 메서드를 호출할 수 있습니다. 우선순위 목록의 어느 위치에서 이런 일이 일어나는지는 어떤 디스크립터 메서드가 정의되어 있고 어떤 식으로 호출되는지에 따라 다릅니다.

디스크립터 호출의 시작점은 결합(binding)입니다, a.x . 어떻게 인자들이 조합되는지는 a 에 따라 다릅니다:

가장 간단하면서도 가장 덜 사용되는 호출은 사용자의 코드가 디스크립터 메서드를 직접 호출할 때입니다: x.__get__(a)

객체 인스턴스에 결합하면, a.x 는 이런 호출로 변환됩니다: type(a).__dict__['x'].__get__(a, type(a)) .

클래스에 결합하면, A.x 는 이런 호출로 변환됩니다: A.__dict__['x'].__get__(None, A) .

A dotted lookup such as super(A, a).x searches a.__class__.__mro__ for a base class B following A and then returns B.__dict__['x'].__get__(a, A) . If not a descriptor, x is returned unchanged.

For instance bindings, the precedence of descriptor invocation depends on which descriptor methods are defined. A descriptor can define any combination of __get__() , __set__() and __delete__() . If it does not define __get__() , then accessing the attribute will return the descriptor object itself unless there is a value in the object’s instance dictionary. If the descriptor defines __set__() and/or __delete__() , it is a data descriptor; if it defines neither, it is a non-data descriptor. Normally, data descriptors define both __get__() and __set__() , while non-data descriptors have just the __get__() method. Data descriptors with __get__() and __set__() (and/or __delete__() ) defined always override a redefinition in an instance dictionary. In contrast, non-data descriptors can be overridden by instances.

Python methods (including those decorated with @staticmethod and @classmethod ) are implemented as non-data descriptors. Accordingly, instances can redefine and override methods. This allows individual instances to acquire behaviors that differ from other instances of the same class.

property() 함수는 데이터 디스크립터로 구현됩니다. 이 때문에, 인스턴스는 프로퍼티(property)의 동작을 변경할 수 없습니다.

3.3.2.4. __slots__ ¶

__slots__ allow us to explicitly declare data members (like properties) and deny the creation of __dict__ and __weakref__ (unless explicitly declared in __slots__ or available in a parent.)

The space saved over using __dict__ can be significant. Attribute lookup speed can be significantly improved as well.

This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. __slots__ reserves space for the declared variables and prevents the automatic creation of __dict__ and __weakref__ for each instance.

Notes on using __slots__ :

When inheriting from a class without __slots__ , the __dict__ and __weakref__ attribute of the instances will always be accessible.

Without a __dict__ variable, instances cannot be assigned new variables not listed in the __slots__ definition. Attempts to assign to an unlisted variable name raises AttributeError . If dynamic assignment of new variables is desired, then add '__dict__' to the sequence of strings in the __slots__ declaration.

Without a __weakref__ variable for each instance, classes defining __slots__ do not support weak references to its instances. If weak reference support is needed, then add '__weakref__' to the sequence of strings in the __slots__ declaration.

__slots__ are implemented at the class level by creating descriptors for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by __slots__ ; otherwise, the class attribute would overwrite the descriptor assignment.

The action of a __slots__ declaration is not limited to the class where it is defined. __slots__ declared in parents are available in child classes. However, child subclasses will get a __dict__ and __weakref__ unless they also define __slots__ (which should only contain names of any additional slots).

클래스가 베이스 클래스의 __slots__ 에 정의된 이름과 같은 이름의 변수를 __slots__ 에 선언한다면, 베이스 클래스가 정의한 변수는 액세스할 수 없는 상태가 됩니다(베이스 클래스로부터 디스크립터를 직접 조회하는 경우는 예외다). 이것은 프로그램을 정의되지 않은 상태로 보내게 됩니다. 미래에는, 이를 방지하기 위한 검사가 추가될 것입니다.

TypeError will be raised if nonempty __slots__ are defined for a class derived from a "variable-length" built-in type such as int , bytes , and tuple .

Any non-string iterable may be assigned to __slots__ .

If a dictionary is used to assign __slots__ , the dictionary keys will be used as the slot names. The values of the dictionary can be used to provide per-attribute docstrings that will be recognised by inspect.getdoc() and displayed in the output of help() .

__class__ assignment works only if both classes have the same __slots__ .

Multiple inheritance with multiple slotted parent classes can be used, but only one parent is allowed to have attributes created by slots (the other bases must have empty slot layouts) - violations raise TypeError .

If an iterator is used for __slots__ then a descriptor is created for each of the iterator’s values. However, the __slots__ attribute will be an empty iterator.

3.3.3. 클래스 생성 커스터마이제이션 ¶

Whenever a class inherits from another class, __init_subclass__() is called on the parent class. This way, it is possible to write classes which change the behavior of subclasses. This is closely related to class decorators, but where class decorators only affect the specific class they’re applied to, __init_subclass__ solely applies to future subclasses of the class defining the method.

이 메서드는 포함하는 클래스의 서브 클래스가 만들어질 때마다 호출됩니다. cls 는 새 서브 클래스입니다. 만약 일반적인 인스턴스 메서드로 정의되면, 이 메서드는 묵시적으로 클래스 메서드로 변경됩니다.

Keyword arguments which are given to a new class are passed to the parent class’s __init_subclass__ . For compatibility with other classes using __init_subclass__ , one should take out the needed keyword arguments and pass the others over to the base class, as in:

기본 구현 object.__init_subclass__ 는 아무 일도 하지 않지만, 인자가 포함되어 호출되면 예외를 발생시킵니다.

메타 클래스 힌트 metaclass 는 나머지 형 절차에 의해 소비되고, __init_subclass__ 로 전달되지 않습니다. 실제 메타 클래스 (명시적인 힌트 대신에) 는 type(cls) 로 액세스할 수 있습니다.

Added in version 3.6.

When a class is created, type.__new__() scans the class variables and makes callbacks to those with a __set_name__() hook.

Automatically called at the time the owning class owner is created. The object has been assigned to name in that class:

If the class variable is assigned after the class is created, __set_name__() will not be called automatically. If needed, __set_name__() can be called directly:

더 자세한 내용은 클래스 객체 만들기 을 참고하십시오.

3.3.3.1. 메타 클래스 ¶

기본적으로, 클래스는 type() 을 사용해서 만들어집니다. 클래스의 바디는 새 이름 공간에서 실행되고, 클래스 이름은 type(name, bases, namespace) 의 결과에 지역적으로 연결됩니다.

클래스를 만드는 과정은 클래스 정의 줄에 metaclass 키워드 인자를 전달하거나, 그런 인자를 포함한 이미 존재하는 클래스를 계승함으로써 커스터마이즈될 수 있습니다. 다음 예에서, MyClass 와 MySubclass 는 모두 Meta 의 인스턴스입니다.

클래스 정의에서 지정된 다른 키워드 인자들은 아래에서 설명되는 모든 메타 클래스 연산들로 전달됩니다.

클래스 정의가 실행될 때, 다음과 같은 단계가 수행됩니다.:

MRO 항목이 결정됩니다;

적절한 메타 클래스가 결정됩니다;

클래스 이름 공간이 준비됩니다;

클래스 바디가 실행됩니다;

클래스 객체가 만들어집니다.

3.3.3.2. MRO 항목 결정하기 ¶

If a base that appears in a class definition is not an instance of type , then an __mro_entries__() method is searched on the base. If an __mro_entries__() method is found, the base is substituted with the result of a call to __mro_entries__() when creating the class. The method is called with the original bases tuple passed to the bases parameter, and must return a tuple of classes that will be used instead of the base. The returned tuple may be empty: in these cases, the original base is ignored.

Dynamically resolve bases that are not instances of type .

Retrieve a class’s “original bases” prior to modifications by __mro_entries__() .

Core support for typing module and generic types.

3.3.3.3. 적절한 메타 클래스 선택하기 ¶

클래스 정의의 적절한 메타 클래스는 다음과 같이 결정됩니다:

베이스와 명시적인 메타 클래스를 주지 않는 경우 type() 이 사용됩니다;

명시적인 메타 클래스가 지정되고, 그것이 type() 의 인스턴스가 아니면 , 그것을 메타 클래스로 사용합니다;

type() 의 인스턴스가 명시적인 메타 클래스로 주어지거나, 베이스가 정의되었으면, 가장 많이 파생된 메타 클래스가 사용됩니다.

가장 많이 파생된 메타 클래스는 명시적으로 지정된 메타 클래스(있다면)와 지정된 모든 베이스 클래스들의 메타 클래스들(즉, type(cls) ) 중에서 선택됩니다. 가장 많이 파생된 메타 클래스는 이들 모두 의 서브 타입(subtype)입니다. 만약 어느 것도 이 조건을 만족하지 못한다면, 클래스 정의는 TypeError 를 발생시키며 실패합니다.

3.3.3.4. 클래스 이름 공간 준비하기 ¶

Once the appropriate metaclass has been identified, then the class namespace is prepared. If the metaclass has a __prepare__ attribute, it is called as namespace = metaclass.__prepare__(name, bases, **kwds) (where the additional keyword arguments, if any, come from the class definition). The __prepare__ method should be implemented as a classmethod . The namespace returned by __prepare__ is passed in to __new__ , but when the final class object is created the namespace is copied into a new dict .

만약 메타 클래스에 __prepare__ 어트리뷰트가 없다면, 클래스 이름 공간은 빈 순서 있는 매핑으로 초기화됩니다.

__prepare__ 이름 공간 훅을 도입했습니다

3.3.3.5. 클래스 바디 실행하기 ¶

클래스 바디는 (대략) exec(body, globals(), namespace) 과같이 실행됩니다. 일반적인 exec() 호출과 주된 차이점은 클래스 정의가 함수 내부에서 이루어질 때 어휘 스코핑(lexical scoping) 이 클래스 바디(모든 메서드들을 포함해서)로 하여금 현재와 외부 스코프에 있는 이름들을 참조하도록 허락한다는 것입니다.

하지만, 클래스 정의가 함수 내부에서 이루어질 때조차도, 클래스 내부에서 정의된 메서드들은 클래스 스코프에서 정의된 이름들을 볼 수 없습니다. 클래스 변수는 인스턴스나 클래스 메서드의 첫 번째 매개변수를 통해 액세스하거나 다음 섹션에서 설명하는 묵시적으로 어휘 스코핑된 __class__ 참조를 통해야 합니다.

3.3.3.6. 클래스 객체 만들기 ¶

일단 클래스 이름 공간이 클래스 바디를 실행함으로써 채워지면, 클래스 객체가 metaclass(name, bases, namespace, **kwds) 을 통해 만들어집니다(여기에서 전달되는 추가적인 키워드 인자들은 __prepare__ 에 전달된 것들과 같습니다).

이 클래스 객체는 super() 에 인자를 주지 않는 경우 참조되는 것입니다. __class__ 는 클래스 바디의 메서드들 중 어느 하나라도 __class__ 나 super 를 참조할 경우 컴파일러에 의해 만들어지는 묵시적인 클로저(closure) 참조입니다. 이것은 인자 없는 형태의 super() 가 어휘 스코핑 기반으로 현재 정의되고 있는 클래스를 올바르게 찾을 수 있도록 합니다. 반면에 현재의 호출에 사용된 클래스나 인스턴스는 메서드로 전달된 첫 번째 인자에 기초해서 식별됩니다.

CPython 구현 상세: CPython 3.6 이상에서, __class__ 셀(cell)은 클래스 이름 공간의 __classcell__ 엔트리로 메타 클래스에 전달됩니다. 만약 존재한다면, 이것은 클래스가 올바르게 초기화되기 위해 type.__new__ 호출까지 거슬러서 전파되어야 합니다. 이렇게 하지 못하면 파이썬 3.8 에서는 RuntimeError 로 이어질 것입니다.

When using the default metaclass type , or any metaclass that ultimately calls type.__new__ , the following additional customization steps are invoked after creating the class object:

The type.__new__ method collects all of the attributes in the class namespace that define a __set_name__() method;

Those __set_name__ methods are called with the class being defined and the assigned name of that particular attribute;

The __init_subclass__() hook is called on the immediate parent of the new class in its method resolution order.

클래스 객체가 만들어진 후에, 클래스 정의에 포함된 클래스 데코레이터들에게 (있다면) 클래스를 전달하고, 그 결과를 클래스가 정의되는 지역 이름 공간에 연결합니다.

type.__new__ 로 새 클래스가 만들어질 때, 이름 공간 매개변수로 제공되는 객체는 새로 만든 순서 있는 매핑으로 복사되고, 원래의 객체는 버립니다. 새 사본은 읽기 전용 프락시(read-only proxy)로 둘러싸이는데, 이것이 클래스 객체의 __dict__ 어트리뷰트가 됩니다.

묵시적인 __class__ 클로저 참조를 설명합니다

3.3.3.7. 메타 클래스의 용도 ¶

메타 클래스의 잠재적인 용도에는 한계가 없습니다. 탐색 된 몇 가지 아이디어들에는 enum, 로깅, 인터페이스 검사, 자동화된 위임(automatic delegation), 자동화된 프로퍼티(properety) 생성, 프락시(proxy), 프레임웍(framework), 자동화된 자원 로킹/동기화(automatic resource locking/synchronization) 등이 있습니다.

3.3.4. 인스턴스 및 서브 클래스 검사 커스터마이제이션 ¶

다음 메서드들은 isinstance() 와 issubclass() 내장 함수들의 기본 동작을 재정의하는 데 사용됩니다.

특히, 메타 클래스 abc.ABCMeta 는 추상 베이스 클래스(Abstract Base Class, ABC)를 다른 ABC를 포함한 임의의 클래스나 형(내장형을 포함합니다)에 “가상 베이스 클래스(virtual base class)”로 추가할 수 있게 하려고 이 메서드들을 구현합니다.

instance 가 (직접적이거나 간접적으로) class 의 인스턴스로 취급될 수 있으면 참을 돌려줍니다. 만약 정의되면, isinstance(instance, class) 를 구현하기 위해 호출됩니다.

subclass 가 (직접적이거나 간접적으로) class 의 서브 클래스로 취급될 수 있으면 참을 돌려줍니다. 만약 정의되면, issubclass(subclass, class) 를 구현하기 위해 호출됩니다.

이 메서드들은 클래스의 형(메타 클래스)에서 조회된다는 것에 주의해야 합니다. 실제 클래스에서 클래스 메서드로 정의될 수 없습니다. 이것은 인스턴스에 대해 호출되는 특수 메서드들의 조회와 일관성 있습니다. 이 경우 인스턴스는 클래스 자체다.

__instancecheck__() 와 __subclasscheck__() 를 통해 isinstance() 와 issubclass() 의 동작을 커스터마이징하는 데 필요한 규약을 포함하는데, 이 기능의 동기는 언어에 추상 베이스 클래스 ( abc 모듈을 보십시오)를 추가하고자 하는 데 있습니다.

3.3.5. 제네릭 형 흉내 내기 ¶

When using type annotations , it is often useful to parameterize a generic type using Python’s square-brackets notation. For example, the annotation list[int] might be used to signify a list in which all the elements are of type int .

Introducing Python’s framework for type annotations

Documentation for objects representing parameterized generic classes

Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers.

A class can generally only be parameterized if it defines the special class method __class_getitem__() .

key 에 있는 형 인자에 의한 제네릭 클래스의 특수화를 나타내는 객체를 돌려줍니다.

When defined on a class, __class_getitem__() is automatically a class method. As such, there is no need for it to be decorated with @classmethod when it is defined.

3.3.5.1. The purpose of __class_getitem__ ¶

The purpose of __class_getitem__() is to allow runtime parameterization of standard-library generic classes in order to more easily apply type hints to these classes.

To implement custom generic classes that can be parameterized at runtime and understood by static type-checkers, users should either inherit from a standard library class that already implements __class_getitem__() , or inherit from typing.Generic , which has its own implementation of __class_getitem__() .

Custom implementations of __class_getitem__() on classes defined outside of the standard library may not be understood by third-party type-checkers such as mypy. Using __class_getitem__() on any class for purposes other than type hinting is discouraged.

3.3.5.2. __class_getitem__ versus __getitem__ ¶

Usually, the subscription of an object using square brackets will call the __getitem__() instance method defined on the object’s class. However, if the object being subscribed is itself a class, the class method __class_getitem__() may be called instead. __class_getitem__() should return a GenericAlias object if it is properly defined.

Presented with the expression obj[x] , the Python interpreter follows something like the following process to decide whether __getitem__() or __class_getitem__() should be called:

In Python, all classes are themselves instances of other classes. The class of a class is known as that class’s metaclass , and most classes have the type class as their metaclass. type does not define __getitem__() , meaning that expressions such as list[int] , dict[str, float] and tuple[str, bytes] all result in __class_getitem__() being called:

However, if a class has a custom metaclass that defines __getitem__() , subscribing the class may result in different behaviour. An example of this can be found in the enum module:

Introducing __class_getitem__() , and outlining when a subscription results in __class_getitem__() being called instead of __getitem__()

3.3.6. 콜러블 객체 흉내 내기 ¶

인스턴스가 함수처럼 “호출될” 때 호출됩니다; 이 메서드가 정의되면, x(arg1, arg2, ...) 는 대략 type(x).__call__(x, arg1, ...) 로 번역됩니다.

3.3.7. 컨테이너형 흉내 내기 ¶

The following methods can be defined to implement container objects. Containers usually are sequences (such as lists or tuples ) or mappings (like dictionaries ), but can represent other containers as well. The first set of methods is used either to emulate a sequence or to emulate a mapping; the difference is that for a sequence, the allowable keys should be the integers k for which 0 <= k < N where N is the length of the sequence, or slice objects, which define a range of items. It is also recommended that mappings provide the methods keys() , values() , items() , get() , clear() , setdefault() , pop() , popitem() , copy() , and update() behaving similar to those for Python’s standard dictionary objects. The collections.abc module provides a MutableMapping abstract base class to help create those methods from a base set of __getitem__() , __setitem__() , __delitem__() , and keys() . Mutable sequences should provide methods append() , count() , index() , extend() , insert() , pop() , remove() , reverse() and sort() , like Python standard list objects. Finally, sequence types should implement addition (meaning concatenation) and multiplication (meaning repetition) by defining the methods __add__() , __radd__() , __iadd__() , __mul__() , __rmul__() and __imul__() described below; they should not define other numerical operators. It is recommended that both mappings and sequences implement the __contains__() method to allow efficient use of the in operator; for mappings, in should search the mapping’s keys; for sequences, it should search through the values. It is further recommended that both mappings and sequences implement the __iter__() method to allow efficient iteration through the container; for mappings, __iter__() should iterate through the object’s keys; for sequences, it should iterate through the values.

Called to implement the built-in function len() . Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __bool__() method and whose __len__() method returns zero is considered to be false in a Boolean context.

CPython 구현 상세: In CPython, the length is required to be at most sys.maxsize . If the length is larger than sys.maxsize some features (such as len() ) may raise OverflowError . To prevent raising OverflowError by truth value testing, an object must define a __bool__() method.

Called to implement operator.length_hint() . Should return an estimated length for the object (which may be greater or less than the actual length). The length must be an integer >= 0. The return value may also be NotImplemented , which is treated the same as if the __length_hint__ method didn’t exist at all. This method is purely an optimization and is never required for correctness.

슬라이싱은 전적으로 다음에 나오는 세 메서드들에의해 수행됩니다

로 번역되고, 다른 형태도 마찬가지입니다. 빠진 슬라이스 항목은 항상 None 으로 채워집니다.

Called to implement evaluation of self[key] . For sequence types, the accepted keys should be integers. Optionally, they may support slice objects as well. Negative index support is also optional. If key is of an inappropriate type, TypeError may be raised; if key is a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised.

for 루프는 시퀀스의 끝을 올바로 감지하기 위해, 잘못된 인덱스에 대해 IndexError 가 일어날 것으로 기대하고 있습니다.

When subscripting a class , the special class method __class_getitem__() may be called instead of __getitem__() . See __class_getitem__ versus __getitem__ for more details.

self[key] 로의 대입을 구현하기 위해 호출됩니다. __getitem__() 과 같은 주의가 필요합니다. 매핑의 경우에는, 객체가 키에 대해 값의 변경이나 새 키의 추가를 허락할 경우, 시퀀스의 경우는 항목이 교체될 수 있을 때만 구현되어야 합니다. 잘못된 key 값의 경우는 __getitem__() 에서와 같은 예외를 일으켜야 합니다.

self[key] 의 삭제를 구현하기 위해 호출됩니다. __getitem__() 과 같은 주의가 필요합니다. 매핑의 경우에는, 객체가 키의 삭제를 허락할 경우, 시퀀스의 경우는 항목이 시퀀스로부터 제거될 수 있을 때만 구현되어야 합니다. 잘못된 key 값의 경우는 __getitem__() 에서와 같은 예외를 일으켜야 합니다.

dict . __getitem__() 이 dict 서브 클래스에서 키가 딕셔너리에 없으면 self[key] 를 구현하기 위해 호출합니다.

This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container.

reversed() 내장 함수가 역 이터레이션(reverse iteration)을 구현하기 위해 (있다면) 호출합니다. 컨테이너에 있는 객체들을 역 순으로 탐색하는 새 이터레이터 객체를 돌려줘야 합니다.

__reversed__() 메서드가 제공되지 않으면, reversed() 내장함수는 시퀀스 프로토콜( __len__() 과 __getitem__() )을 대안으로 사용합니다. 시퀀스 프로토콜을 지원하는 객체들은 reversed() 가 제공하는 것보다 더 효율적인 구현을 제공할 수 있을 때만 __reversed__() 를 제공해야 합니다.

멤버십 검사 연산자들( in 과 not in ) 은 보통 컨테이너에 대한 이터레이션으로 구현됩니다. 하지만, 컨테이너 객체는 더 효율적인 구현을 다음과 같은 특수 메서드를 통해 제공할 수 있습니다. 이 경우 객체는 이터러블일 필요도 없습니다.

멤버십 검사 연산자를 구현하기 위해 호출됩니다. item 이 self 에 있으면 참을, 그렇지 않으면 거짓을 돌려줘야 합니다. 매핑 객체의 경우, 키-값 쌍이 아니라 매핑의 키가 고려되어야 합니다.

__contains__() 를 정의하지 않는 객체의 경우, 멤버십 검사는 먼저 __iter__() 를 통한 이터레이션을 시도한 후, __getitem__() 을 통한 낡은 시퀀스 이터레이션 프로토콜을 시도합니다. 언어 레퍼런스의 이 절 을 참고하십시오.

3.3.8. 숫자 형 흉내 내기 ¶

숫자 형을 흉내 내기 위해 다음과 같은 메서드들을 정의할 수 있습니다. 구현되는 특별한 종류의 숫자에 의해 지원되지 않는 연산들(예를 들어, 정수가 아닌 숫자들에 대한 비트 연산들)에 대응하는 메서드들을 정의되지 않은 채로 남겨두어야 합니다.

These methods are called to implement the binary arithmetic operations ( + , - , * , @ , / , // , % , divmod() , pow() , ** , << , >> , & , ^ , | ). For instance, to evaluate the expression x + y , where x is an instance of a class that has an __add__() method, type(x).__add__(x, y) is called. The __divmod__() method should be the equivalent to using __floordiv__() and __mod__() ; it should not be related to __truediv__() . Note that __pow__() should be defined to accept an optional third argument if the ternary version of the built-in pow() function is to be supported.

If one of those methods does not support the operation with the supplied arguments, it should return NotImplemented .

These methods are called to implement the binary arithmetic operations ( + , - , * , @ , / , // , % , divmod() , pow() , ** , << , >> , & , ^ , | ) with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation [ 3 ] and the operands are of different types. [ 4 ] For instance, to evaluate the expression x - y , where y is an instance of a class that has an __rsub__() method, type(y).__rsub__(y, x) is called if type(x).__sub__(x, y) returns NotImplemented .

삼 항 pow() 는 __rpow__() 를 호출하려고 시도하지 않음에 주의해야 합니다 (그렇게 하려면 코어션 규칙이 너무 복잡해집니다).

만약 오른쪽 피연산자의 형이 왼쪽 피연산자의 형의 서브 클래스이고, 그 서브 클래스가 연산의 뒤집힌 메서드의 다른 구현을 제공하면, 이 메서드가 왼쪽 연산자의 뒤집히지 않은 메서드보다 먼저 호출됩니다. 이 동작은 서브 클래스가 조상들의 연산을 재정의할 수 있도록 합니다.

These methods are called to implement the augmented arithmetic assignments ( += , -= , *= , @= , /= , //= , %= , **= , <<= , >>= , &= , ^= , |= ). These methods should attempt to do the operation in-place (modifying self ) and return the result (which could be, but does not have to be, self ). If a specific method is not defined, or if that method returns NotImplemented , the augmented assignment falls back to the normal methods. For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y) . If __iadd__() does not exist, or if x.__iadd__(y) returns NotImplemented , x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y . In certain situations, augmented assignment can result in unexpected errors (see 덧셈은 작동하는데, 왜 a_tuple[i] += [‘item’]이 예외를 일으킵니까? ), but this behavior is in fact part of the data model.

일 항 산술 연산( - , + , abs() , ~ )을 구현하기 위해 호출됩니다.

내장 함수 complex() , int() , float() 를 구현하기 위해 호출됩니다. 적절한 형의 값을 돌려줘야 합니다.

operator.index() 를 구현하기 위해 호출되고, 파이썬이 숫자 객체를 정수 객체로 손실 없이 변환해야 할 때(슬라이싱이나 내장 bin() , hex() , oct() 함수들에서와같이)마다 호출됩니다. 이 메서드의 존재는 숫자 객체가 정수 형임을 가리킵니다. 반드시 정수를 돌려줘야 합니다.

__int__() , __float__() 및 __complex__() 가 정의되어 있지 않으면, 해당 내장 함수 int() , float() 및 complex() 는 __index__() 를 사용합니다.

내장 함수 round() 와 math 함수 trunc() , floor() , ceil() 을 구현하기 위해 호출됩니다. ndigits 가 __round__() 로 전달되지 않는 한, 이 메서드들은 모두 Integral (보통 int ) 로 잘린 객체의 값을 돌려줘야 합니다.

The built-in function int() falls back to __trunc__() if neither __int__() nor __index__() is defined.

버전 3.11에서 변경: The delegation of int() to __trunc__() is deprecated.

3.3.9. with 문 컨텍스트 관리자 ¶

컨텍스트 관리자 (context manager) 는 with 문을 실행할 때 자리 잡는 실행 컨텍스트(context)를 정의하는 객체입니다. 코드 블록의 실행을 위해, 컨텍스트 관리자는 원하는 실행시간 컨텍스트로의 진입과 탈출을 처리합니다. 컨텍스트 관리자는 보통 with 문( with 문 섹션에서 설명합니다)으로 시작되지만, 그들의 메서드를 호출해서 직접 사용할 수도 있습니다.

컨텍스트 관리자의 전형적인 용도에는 다양한 종류의 전역 상태(global state)를 보관하고 복구하는 것, 자원을 로킹(locking)하고 언로킹(unlocking)하는 것, 열린 파일을 닫는 것 등이 있습니다.

컨텍스트 관리자에 대한 더 자세한 정보는 컨텍스트 관리자 형 에 나옵니다.

이 객체와 연관된 실행시간 컨텍스트에 진입합니다. with 문은 as 절로 지정된 대상이 있다면, 이 메서드의 반환 값을 연결합니다.

이 객체와 연관된 실행시간 컨텍스트를 종료합니다. 매개변수들은 컨텍스트에서 벗어나게 만든 예외를 기술합니다. 만약 컨텍스트가 예외 없이 종료한다면, 세 인자 모두 None 이 됩니다.

만약 예외가 제공되고, 메서드가 예외를 중지시키고 싶으면 (즉 확산하는 것을 막으려면) 참(true)을 돌려줘야 합니다. 그렇지 않으면 예외는 이 메서드가 종료한 후에 계속 진행됩니다.

Note that __exit__() methods should not reraise the passed-in exception; this is the caller’s responsibility.

파이썬 with 문에 대한 규격, 배경, 예.

3.3.10. Customizing positional arguments in class pattern matching ¶

When using a class name in a pattern, positional arguments in the pattern are not allowed by default, i.e. case MyClass(x, y) is typically invalid without special support in MyClass . To be able to use that kind of pattern, the class needs to define a __match_args__ attribute.

This class variable can be assigned a tuple of strings. When this class is used in a class pattern with positional arguments, each positional argument will be converted into a keyword argument, using the corresponding value in __match_args__ as the keyword. The absence of this attribute is equivalent to setting it to () .

For example, if MyClass.__match_args__ is ("left", "center", "right") that means that case MyClass(x, y) is equivalent to case MyClass(left=x, center=y) . Note that the number of arguments in the pattern must be smaller than or equal to the number of elements in __match_args__ ; if it is larger, the pattern match attempt will raise a TypeError .

The specification for the Python match statement.

3.3.11. Emulating buffer types ¶

The buffer protocol provides a way for Python objects to expose efficient access to a low-level memory array. This protocol is implemented by builtin types such as bytes and memoryview , and third-party libraries may define additional buffer types.

While buffer types are usually implemented in C, it is also possible to implement the protocol in Python.

Called when a buffer is requested from self (for example, by the memoryview constructor). The flags argument is an integer representing the kind of buffer requested, affecting for example whether the returned buffer is read-only or writable. inspect.BufferFlags provides a convenient way to interpret the flags. The method must return a memoryview object.

Called when a buffer is no longer needed. The buffer argument is a memoryview object that was previously returned by __buffer__() . The method must release any resources associated with the buffer. This method should return None . Buffer objects that do not need to perform any cleanup are not required to implement this method.

Added in version 3.12.

Introduces the Python __buffer__ and __release_buffer__ methods.

ABC for buffer types.

3.3.12. 특수 메서드 조회 ¶

사용자 정의 클래스의 경우, 묵시적인 특수 메서드의 호출은 객체의 인스턴스 딕셔너리가 아닌 객체의 형에 정의되어 있을 때만 올바르게 동작함이 보장됩니다. 이런 동작은 다음과 같은 코드가 예외를 일으키는 원인입니다:

The rationale behind this behaviour lies with a number of special methods such as __hash__() and __repr__() that are implemented by all objects, including type objects. If the implicit lookup of these methods used the conventional lookup process, they would fail when invoked on the type object itself:

클래스의 연결되지 않은 메서드를 호출하려는 이런 식의 잘못된 시도는 종종 ‘메타 클래스 혼란(metaclass confusion)’ 이라고 불리고, 특수 메서드를 조회할 때 인스턴스를 우회하는 방법으로 피할 수 있습니다.

In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the __getattribute__() method even of the object’s metaclass:

Bypassing the __getattribute__() machinery in this fashion provides significant scope for speed optimisations within the interpreter, at the cost of some flexibility in the handling of special methods (the special method must be set on the class object itself in order to be consistently invoked by the interpreter).

3.4. 코루틴(Coroutines) ¶

3.4.1. 어웨이터블 객체(awaitable objects) ¶.

An awaitable object generally implements an __await__() method. Coroutine objects returned from async def functions are awaitable.

The generator iterator objects returned from generators decorated with types.coroutine() are also awaitable, but they do not implement __await__() .

이터레이터 를 돌려줘야 합니다. 어웨이터블 객체를 구현하기 위해 사용되어야 합니다. 예를 들어, asyncio.Future 는 await 표현식과 호환되기 위해 이 메서드를 구현합니다.

The language doesn’t place any restriction on the type or value of the objects yielded by the iterator returned by __await__ , as this is specific to the implementation of the asynchronous execution framework (e.g. asyncio ) that will be managing the awaitable object.

Added in version 3.5.

PEP 492 가 어웨이터블 객체에 대한 더 자세한 정보를 포함하고 있습니다.

3.4.2. 코루틴 객체(Coroutine Objects) ¶

Coroutine objects are awaitable objects. A coroutine’s execution can be controlled by calling __await__() and iterating over the result. When the coroutine has finished executing and returns, the iterator raises StopIteration , and the exception’s value attribute holds the return value. If the coroutine raises an exception, it is propagated by the iterator. Coroutines should not directly raise unhandled StopIteration exceptions.

코루틴은 다음에 나열하는 메서드들 또한 갖고 있는데, 제너레이터( 제너레이터-이터레이터 메서드 를 보십시오)의 것들과 닮았습니다. 하지만, 제너레이터와는 달리, 코루틴은 이터레이션을 직접 지원하지는 않습니다.

버전 3.5.2에서 변경: 코루틴을 두 번 await 하면 RuntimeError 를 일으킵니다.

Starts or resumes execution of the coroutine. If value is None , this is equivalent to advancing the iterator returned by __await__() . If value is not None , this method delegates to the send() method of the iterator that caused the coroutine to suspend. The result (return value, StopIteration , or other exception) is the same as when iterating over the __await__() return value, described above.

Raises the specified exception in the coroutine. This method delegates to the throw() method of the iterator that caused the coroutine to suspend, if it has such a method. Otherwise, the exception is raised at the suspension point. The result (return value, StopIteration , or other exception) is the same as when iterating over the __await__() return value, described above. If the exception is not caught in the coroutine, it propagates back to the caller.

버전 3.12에서 변경: The second signature (type[, value[, traceback]]) is deprecated and may be removed in a future version of Python.

코루틴이 자신을 정리하고 종료하도록 만듭니다. 만약 코루틴이 일시 중지 중이면, 이 메서드는 먼저 코루틴이 일시 중지되도록 한 이터레이터의 close() 메서드로 위임합니다(그런 메서드를 가지는 경우). 그런 다음 일시 중지지점에서 GeneratorExit 를 발생시키는데, 코루틴이 즉시 자신을 정리하도록 만듭니다. 마지막으로 코루틴에 실행을 종료했다고 표시하는데, 아직 시작하지조차 않았을 때도 그렇다.

코루틴 객체가 파괴될 때는 위의 프로세스에 따라 자동으로 닫힙니다(closed).

3.4.3. 비동기 이터레이터(Asynchronous Iterators) ¶

비동기 이터레이터 는 자신의 __anext__ 메서드에서 비동기 코드를 호출할 수 있습니다.

비동기 이터레이터는 async for 문에서 사용될 수 있습니다.

비동기 이터레이터 객체를 돌려줘야 합니다.

이터레이터의 다음 값을 주는 어웨이터블 을 돌려줘야 합니다. 이터레이션이 끝나면 StopAsyncIteration 에러를 일으켜야 합니다.

비동기 이터러블 객체의 예:

버전 3.7에서 변경: Prior to Python 3.7, __aiter__() could return an awaitable that would resolve to an asynchronous iterator .

Starting with Python 3.7, __aiter__() must return an asynchronous iterator object. Returning anything else will result in a TypeError error.

3.4.4. 비동기 컨텍스트 관리자 ¶

비동기 컨텍스트 관리자(asynchronous context manager) 는 __aenter__ 와 __aexit__ 메서드에서 실행을 일시 중지할 수 있는 컨텍스트 관리자 입니다.

비동기 컨텍스트 관리자는 async with 문에서 사용될 수 있습니다.

Semantically similar to __enter__() , the only difference being that it must return an awaitable .

Semantically similar to __exit__() , the only difference being that it must return an awaitable .

비동기 컨텍스트 관리자 클래스의 예:

  • 3.1. 객체, 값, 형
  • 3.2.1. None
  • 3.2.2. NotImplemented
  • 3.2.3. Ellipsis
  • 3.2.4.1. numbers.Integral
  • 3.2.4.2. numbers.Real ( float )
  • 3.2.4.3. numbers.Complex ( complex )
  • 3.2.5.1. 불변 시퀀스
  • 3.2.5.2. 가변 시퀀스
  • 3.2.6. 집합 형들(Set types)
  • 3.2.7.1. 딕셔너리(Dictionaries)
  • 3.2.8.1.1. Special read-only attributes
  • 3.2.8.1.2. Special writable attributes
  • 3.2.8.2. 인스턴스 메서드(Instance methods)
  • 3.2.8.3. 제너레이터 함수(Generator functions)
  • 3.2.8.4. 코루틴 함수(Coroutine functions)
  • 3.2.8.5. 비동기 제너레이터 함수(Asynchronous generator functions)
  • 3.2.8.6. 내장 함수(Built-in functions)
  • 3.2.8.7. 내장 메서드(Built-in methods)
  • 3.2.8.8. 클래스(Classes)
  • 3.2.8.9. 클래스 인스턴스(Class Instances)
  • 3.2.9. 모듈(Modules)
  • 3.2.10. 사용자 정의 클래스(Custom classes)
  • 3.2.11. 클래스 인스턴스(Class instances)
  • 3.2.12. I/O 객체 (파일 객체라고도 알려져 있습니다)
  • 3.2.13.1.1. Special read-only attributes
  • 3.2.13.1.2. Methods on code objects
  • 3.2.13.2.1. Special read-only attributes
  • 3.2.13.2.2. Special writable attributes
  • 3.2.13.2.3. Frame object methods
  • 3.2.13.3. 트레이스백 객체(Traceback objects)
  • 3.2.13.4. 슬라이스 객체(Slice objects)
  • 3.2.13.5. 스태틱 메서드 객체(Static method objects)
  • 3.2.13.6. 클래스 메서드 객체(Class method objects)
  • 3.3.1. 기본적인 커스터마이제이션
  • 3.3.2.1. 모듈 어트리뷰트 액세스 커스터마이제이션
  • 3.3.2.2. 디스크립터 구현하기
  • 3.3.2.3. 디스크립터 호출하기
  • 3.3.2.4. __slots__
  • 3.3.3.1. 메타 클래스
  • 3.3.3.2. MRO 항목 결정하기
  • 3.3.3.3. 적절한 메타 클래스 선택하기
  • 3.3.3.4. 클래스 이름 공간 준비하기
  • 3.3.3.5. 클래스 바디 실행하기
  • 3.3.3.6. 클래스 객체 만들기
  • 3.3.3.7. 메타 클래스의 용도
  • 3.3.4. 인스턴스 및 서브 클래스 검사 커스터마이제이션
  • 3.3.5.1. The purpose of __class_getitem__
  • 3.3.5.2. __class_getitem__ versus __getitem__
  • 3.3.6. 콜러블 객체 흉내 내기
  • 3.3.7. 컨테이너형 흉내 내기
  • 3.3.8. 숫자 형 흉내 내기
  • 3.3.9. with 문 컨텍스트 관리자
  • 3.3.10. Customizing positional arguments in class pattern matching
  • 3.3.11. Emulating buffer types
  • 3.3.12. 특수 메서드 조회
  • 3.4.1. 어웨이터블 객체(Awaitable Objects)
  • 3.4.2. 코루틴 객체(Coroutine Objects)
  • 3.4.3. 비동기 이터레이터(Asynchronous Iterators)
  • 3.4.4. 비동기 컨텍스트 관리자

IMAGES

  1. Fix TypeError: 'str' object does not support item assignment in Python

    python dict 'str' object does not support item assignment

  2. Fix TypeError: 'str' object does not support item assignment in Python

    python dict 'str' object does not support item assignment

  3. python

    python dict 'str' object does not support item assignment

  4. Python :'str' object does not support item assignment(5solution)

    python dict 'str' object does not support item assignment

  5. Python String Error: 'str' Object Does Not Support Item Assignment

    python dict 'str' object does not support item assignment

  6. [Solved] TypeError: 'str' Object Does Not Support Item Assignment

    python dict 'str' object does not support item assignment

VIDEO

  1. Python Tutorial

  2. How to Remove Duplicates From a Python List (And Keep Order)

  3. mysql python AttributeError str object has no attribute cursor

  4. Understanding and Resolving the 'TypeError: 'set' object is not subscriptable'

  5. Python Dicts vs. Python Lists

  6. 'str' object has no attribute 'decode'. Python 3 error?

COMMENTS

  1. 'str' object does not support item assignment

    5. Strings in Python are immutable (you cannot change them inplace). What you are trying to do can be done in many ways: Copy the string: foo = 'Hello'. bar = foo. Create a new string by joining all characters of the old string: new_string = ''.join(c for c in oldstring) Slice and copy:

  2. [Solved] TypeError: 'str' Object Does Not Support Item Assignment

    TypeError: 'str' Object Does Not Support Item Assignment in Pandas Data Frame The following program attempts to add a new column into the data frame import numpy as np import pandas as pd import random as rnd df = pd.read_csv('sample.csv') for dataset in df: dataset['Column'] = 1

  3. Fix Python TypeError: 'str' object does not support item assignment

    greet[0] = 'J'. TypeError: 'str' object does not support item assignment. To fix this error, you can create a new string with the desired modifications, instead of trying to modify the original string. This can be done by calling the replace() method from the string. See the example below: old_str = 'Hello, world!'.

  4. Python 'str' object does not support item assignment solution

    This code replaces the character at name[c] with an empty string. We have created a separate variable called "final_username". This variable is initially an empty string.

  5. TypeError: 'str' object does not support item assignment

    We accessed the first nested array (index 0) and then updated the value of the first item in the nested array.. Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(a_list) - 1. # Checking what type a variable stores The Python "TypeError: 'float' object does not support item assignment" is caused when we try to mutate the ...

  6. Fix "str object does not support item assignment python"

    Understanding the Python string object. In Python programming, a string is a sequence of characters, enclosed within quotation marks. It is one of the built-in data types in Python and can be defined using either single (' ') or double (" ") quotation marks.

  7. How to Solve Python TypeError: 'str' object does not support item

    Python TypeError: 'str' object does not support item assignment. ... TypeError: 'str' object does not support item assignment. We cannot change the character at position -1 (last character) because strings are immutable. We need to create a modified copy of a string, for example using ...

  8. How to Fix STR Object Does Not Support Item Assignment Error in Python

    Python 3 Basic Tkinter Python Modules JavaScript Python Numpy Git Matplotlib PyQt5 Data Structure Algorithm HowTo Python Scipy Python Python Tkinter Batch PowerShell Python Pandas Numpy Python Flask Django Matplotlib Docker Plotly Seaborn Matlab Linux Git C Cpp HTML JavaScript jQuery Python Pygame TensorFlow TypeScript Angular React CSS PHP ...

  9. Python String Error: 'str' Object Does Not Support Item Assignment

    Understanding the 'str' object. The 'str' object is a built-in data type in Python and stands for string. Strings are a collection of characters enclosed within single or double quotes, and in Python, these strings are immutable.

  10. How to Fix the Python Error: typeerror: 'str' object does not support

    But if we tried to change an element of a string using the same format it would produce the "typeerror: 'str' object does not support item assignment". ... The next part of the assignment is where we see Python's true relationship with strings. The x[1::] statement reads the data from the original x assignment. However, it begins ...

  11. TypeError: 'str' object does not support item assignment

    The TypeError: 'str' object does not support item assignment error occurs when we try to change the contents of the string using an assignment operator.

  12. Python's Assignment Operator: Write Robust Assignments

    To create a new variable or to update the value of an existing one in Python, you'll use an assignment statement. This statement has the following three components: A left operand, which must be a variable. The assignment operator ( =) A right operand, which can be a concrete value, an object, or an expression.

  13. 'str' object does not support item assignment (Python)

    Assuming that the parameter text is a string, the line for letter in text[1]: doesn't make much sense to me since text[1] is a single character. What's the point of iterating over a one-letter string? However, if text is a list of strings, then your function doesn't throw any exceptions, it simply returns the string that results from replacing in the first string (text[0]) all the letters of ...

  14. TypeError: NoneType object does not support item assignment

    If the variable stores a None value, we set it to an empty dictionary. # Track down where the variable got assigned a None value You have to figure out where the variable got assigned a None value in your code and correct the assignment to a list or a dictionary.. The most common sources of None values are:. Having a function that doesn't return anything (returns None implicitly).

  15. Python TypeError: 'str' object does not support item assignment Solution

    There are many ways to solve the above problem, the easiest way is by converting the string into a list using the list () function. Change the first character and change the list back to the string using the join () method. #string. string = "this is a string" #convert the string to list.

  16. 'str' object does not support item assignment

    The official dedicated python forum. So currently i am experiencing an issue where i am trying to assign a value in a dictionary to an index value of a string The code goes as follows searchValues = values = {} versions = 5 for v in rang ... 'str' object does not support item assignment. Python Forum; Python Coding; General Coding Help; Thread ...

  17. TypeError: 'src' object does not support item assignment

    The assignment str[i] = str[j] is working inconsistently. Please refer to the screenshots and let me know if I am missing something. We are receiving TypeError: 'src' object does not support item assignment Regards, Praveen. Thank you!

  18. How to solve"TypeError: 'str' object does not support item assignment

    Environments. YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):. Notebooks with free GPU: ; Google Cloud Deep Learning VM. See GCP Quickstart Guide; Amazon Deep Learning AMI. See AWS Quickstart Guide; Docker Image.

  19. Dictionary error :"TypeError: 'str' object does not support item

    Check in your code for assignment to dictionary. The variable dictionary isn't a dictionary, but a string, so somewhere in your code will be something like: dictionary = " evaluates to string "

  20. How to Learn Python from Scratch in 2024

    In python there is no character data type, a character is a string of length one. It is represented by str class. Strings in Python can be created using single quotes or double quotes or even triple quotes. ... in String1[2] = 'p' TypeError: 'str' object does not support item assignment Traceback (most recent call last): File "/home ...

  21. 3. 파이썬의 간략한 소개

    파이썬의 간략한 소개 — Python 3.14.0a0 문서. 3. 파이썬의 간략한 소개 ¶. 다음에 나올 예에서, 입력과 출력은 프롬프트 ( >>> 와 …. )의 존재 여부로 구분됩니다: 예제를 실행하기 위해서는 프롬프트가 나올 때 프롬프트 뒤에 오는 모든 것들을 입력해야 합니다 ...

  22. python3 修改字符串的四种方法 错误 'str' object does not support item assignment 解决

    在Python中,字符串是不可变类型,即无法直接修改字符串的某一位字符。. 直接修改会报错:'str' object does not support item assignment因此改变一个字符串的元素需要新建一个新的字符串。. 常见的修改方法有以下4种。. 方法1:将字符串转换成列表后修改值,然后用join ...

  23. 인자 구문 분석과 값 구축

    where object is the Python object to be converted and address is the void * argument that was passed to the PyArg_Parse* function. The returned status should be 1 for a successful conversion and 0 if the conversion has failed. When the conversion fails, the converter function should raise an exception and leave the content of address unmodified.. converter가 Py_CLEANUP_SUPPORTED 를 ...

  24. TypeError: 'str' object does not support item assignment (Python)

    Strings are immutable. You can not change the characters in a string, but have to create a new string. If you want to use item assignment, you can transform it into a list, manipulate the list, then join it back to a string.

  25. 5. 資料結構

    資料結構 — Python 3.14.0a0 說明文件. 5. 資料結構 ¶. 這個章節將會更深入的介紹一些你已經學過的東西的細節上,並且加入一些你還沒有接觸過的部分。. 5.1. 進一步了解 List(串列) ¶. List(串列)這個資料型態,具有更多操作的方法。. 下面條列了所有關於 list ...

  26. Python TypeError: 'type' object does not support item assignment

    TypeError: 'type' object does not support item assignment for "dict[n] = n" Any help or suggestion? Thank you so much! python; Share. Follow ... Not only is this overwriting python's dict, (see mgilson's comment) but this is the wrong data structure for the project. You should use a list instead (or a set if you have unique unordered values)

  27. pickle

    Optionally, an iterator (and not a sequence) yielding successive items. These items will be appended to the object either using obj.append(item) or, in batch, using obj.extend(list_of_items). This is primarily used for list subclasses, but may be used by other classes as long as they have append and extend methods with the appropriate signature.

  28. python

    Edit: There is a good reason for the above design in the type system and I will give a few: 1. dict type is a concrete type so it will actually get used in a program. 2. Because of the above mentioned, it was designed the way it was to avoid things like this: a: dict[int, int] = {} b: dict[int, int | str] = a.

  29. 3. 데이터 모델

    Sequences also support slicing: a[i:j] selects all items with index k such that i <= k < j. When used as an expression, a slice is a sequence of the same type. ... A module object does not contain the code object used to initialize the module (since it isn't needed once the initialization is done). ... , dict[str, float] and tuple[str, bytes ...

  30. Python: how to determine if an object is iterable?

    Checking isinstance(obj, Iterable) detects classes that are registered as Iterable or that have an __iter__() method, but it does not detect classes that iterate with the __getitem__() method. The only reliable way to determine whether an object is iterable is to call iter(obj). edited Mar 4, 2022 at 17:02.